From 1de5641c319ad60167be9c303490724fbfa0ca9f Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 2 Sep 2025 15:57:33 +0000 Subject: [PATCH 1/2] feat: add address groups API PiperOrigin-RevId: 802118490 Source-Link: https://github.com/googleapis/googleapis/commit/3346b304dc552904d9d3dd6e8a83ee473e0673b3 Source-Link: https://github.com/googleapis/googleapis-gen/commit/066cd0c9c56da22b0d52b4b893d190b9d2b2185a Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLW5ldHdvcmstc2VjdXJpdHkvLk93bEJvdC55YW1sIiwiaCI6IjA2NmNkMGM5YzU2ZGEyMmIwZDUyYjRiODkzZDE5MGI5ZDJiMjE4NWEifQ== --- .../v1/.coveragerc | 13 + .../google-cloud-network-security/v1/.flake8 | 34 + .../google-cloud-network-security/v1/LICENSE | 202 + .../v1/MANIFEST.in | 20 + .../v1/README.rst | 143 + .../v1/docs/_static/custom.css | 20 + .../v1/docs/_templates/layout.html | 50 + .../v1/docs/conf.py | 385 + .../v1/docs/index.rst | 10 + .../v1/docs/multiprocessing.rst | 7 + .../address_group_service.rst | 10 + .../network_security_v1/network_security.rst | 10 + .../organization_address_group_service.rst | 10 + .../v1/docs/network_security_v1/services_.rst | 8 + .../v1/docs/network_security_v1/types_.rst | 6 + .../google/cloud/network_security/__init__.py | 111 + .../cloud/network_security/gapic_version.py | 16 + .../v1/google/cloud/network_security/py.typed | 2 + .../cloud/network_security_v1/__init__.py | 112 + .../network_security_v1/gapic_metadata.json | 561 + .../network_security_v1/gapic_version.py | 16 + .../google/cloud/network_security_v1/py.typed | 2 + .../network_security_v1/services/__init__.py | 15 + .../address_group_service/__init__.py | 22 + .../address_group_service/async_client.py | 2047 +++ .../services/address_group_service/client.py | 2422 +++ .../services/address_group_service/pagers.py | 306 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../address_group_service/transports/base.py | 409 + .../address_group_service/transports/grpc.py | 768 + .../transports/grpc_asyncio.py | 874 + .../address_group_service/transports/rest.py | 3043 ++++ .../transports/rest_base.py | 800 + .../services/network_security/__init__.py | 22 + .../services/network_security/async_client.py | 2866 +++ .../services/network_security/client.py | 3253 ++++ .../services/network_security/pagers.py | 446 + .../network_security/transports/README.rst | 9 + .../network_security/transports/__init__.py | 38 + .../network_security/transports/base.py | 497 + .../network_security/transports/grpc.py | 933 + .../transports/grpc_asyncio.py | 1069 ++ .../network_security/transports/rest.py | 4105 +++++ .../network_security/transports/rest_base.py | 1036 ++ .../__init__.py | 22 + .../async_client.py | 2046 +++ .../client.py | 2421 +++ .../pagers.py | 306 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 409 + .../transports/grpc.py | 767 + .../transports/grpc_asyncio.py | 873 + .../transports/rest.py | 3042 ++++ .../transports/rest_base.py | 800 + .../network_security_v1/types/__init__.py | 106 + .../types/address_group.py | 625 + .../types/authorization_policy.py | 425 + .../types/client_tls_policy.py | 271 + .../cloud/network_security_v1/types/common.py | 95 + .../types/network_security.py | 26 + .../types/server_tls_policy.py | 296 + .../cloud/network_security_v1/types/tls.py | 154 + .../google-cloud-network-security/v1/mypy.ini | 3 + .../v1/noxfile.py | 592 + ...p_service_add_address_group_items_async.py | 57 + ...up_service_add_address_group_items_sync.py | 57 + ...service_clone_address_group_items_async.py | 57 + ..._service_clone_address_group_items_sync.py | 57 + ...roup_service_create_address_group_async.py | 63 + ...group_service_create_address_group_sync.py | 63 + ...roup_service_delete_address_group_async.py | 56 + ...group_service_delete_address_group_sync.py | 56 + ...s_group_service_get_address_group_async.py | 52 + ...ss_group_service_get_address_group_sync.py | 52 + ...ice_list_address_group_references_async.py | 53 + ...vice_list_address_group_references_sync.py | 53 + ...group_service_list_address_groups_async.py | 53 + ..._group_service_list_address_groups_sync.py | 53 + ...ervice_remove_address_group_items_async.py | 57 + ...service_remove_address_group_items_sync.py | 57 + ...roup_service_update_address_group_async.py | 61 + ...group_service_update_address_group_sync.py | 61 + ...urity_create_authorization_policy_async.py | 62 + ...curity_create_authorization_policy_sync.py | 62 + ...security_create_client_tls_policy_async.py | 61 + ..._security_create_client_tls_policy_sync.py | 61 + ...security_create_server_tls_policy_async.py | 61 + ..._security_create_server_tls_policy_sync.py | 61 + ...urity_delete_authorization_policy_async.py | 56 + ...curity_delete_authorization_policy_sync.py | 56 + ...security_delete_client_tls_policy_async.py | 56 + ..._security_delete_client_tls_policy_sync.py | 56 + ...security_delete_server_tls_policy_async.py | 56 + ..._security_delete_server_tls_policy_sync.py | 56 + ...security_get_authorization_policy_async.py | 52 + ..._security_get_authorization_policy_sync.py | 52 + ...rk_security_get_client_tls_policy_async.py | 52 + ...ork_security_get_client_tls_policy_sync.py | 52 + ...rk_security_get_server_tls_policy_async.py | 52 + ...ork_security_get_server_tls_policy_sync.py | 52 + ...urity_list_authorization_policies_async.py | 53 + ...curity_list_authorization_policies_sync.py | 53 + ...security_list_client_tls_policies_async.py | 53 + ..._security_list_client_tls_policies_sync.py | 53 + ...security_list_server_tls_policies_async.py | 53 + ..._security_list_server_tls_policies_sync.py | 53 + ...urity_update_authorization_policy_async.py | 60 + ...curity_update_authorization_policy_sync.py | 60 + ...security_update_client_tls_policy_async.py | 59 + ..._security_update_client_tls_policy_sync.py | 59 + ...security_update_server_tls_policy_async.py | 59 + ..._security_update_server_tls_policy_sync.py | 59 + ...p_service_add_address_group_items_async.py | 57 + ...up_service_add_address_group_items_sync.py | 57 + ...service_clone_address_group_items_async.py | 57 + ..._service_clone_address_group_items_sync.py | 57 + ...roup_service_create_address_group_async.py | 63 + ...group_service_create_address_group_sync.py | 63 + ...roup_service_delete_address_group_async.py | 56 + ...group_service_delete_address_group_sync.py | 56 + ...s_group_service_get_address_group_async.py | 52 + ...ss_group_service_get_address_group_sync.py | 52 + ...ice_list_address_group_references_async.py | 53 + ...vice_list_address_group_references_sync.py | 53 + ...group_service_list_address_groups_async.py | 53 + ..._group_service_list_address_groups_sync.py | 53 + ...ervice_remove_address_group_items_async.py | 57 + ...service_remove_address_group_items_sync.py | 57 + ...roup_service_update_address_group_async.py | 61 + ...group_service_update_address_group_sync.py | 61 + ...adata_google.cloud.networksecurity.v1.json | 5496 ++++++ .../fixup_network_security_v1_keywords.py | 199 + .../google-cloud-network-security/v1/setup.py | 99 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.13.txt | 12 + .../v1/testing/constraints-3.7.txt | 11 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../gapic/network_security_v1/__init__.py | 16 + .../test_address_group_service.py | 10025 +++++++++++ .../test_network_security.py | 14565 ++++++++++++++++ ...test_organization_address_group_service.py | 10025 +++++++++++ .../v1alpha1/.coveragerc | 13 + .../v1alpha1/.flake8 | 34 + .../v1alpha1/LICENSE | 202 + .../v1alpha1/MANIFEST.in | 20 + .../v1alpha1/README.rst | 143 + .../v1alpha1/docs/_static/custom.css | 20 + .../v1alpha1/docs/_templates/layout.html | 50 + .../v1alpha1/docs/conf.py | 385 + .../v1alpha1/docs/index.rst | 10 + .../v1alpha1/docs/multiprocessing.rst | 7 + .../network_security.rst | 10 + .../network_security_v1alpha1/services_.rst | 6 + .../docs/network_security_v1alpha1/types_.rst | 6 + .../google/cloud/network_security/__init__.py | 51 + .../cloud/network_security/gapic_version.py | 16 + .../google/cloud/network_security/py.typed | 2 + .../network_security_v1alpha1/__init__.py | 52 + .../gapic_metadata.json | 103 + .../gapic_version.py | 16 + .../cloud/network_security_v1alpha1/py.typed | 2 + .../services/__init__.py | 15 + .../services/network_security/__init__.py | 22 + .../services/network_security/async_client.py | 1539 ++ .../services/network_security/client.py | 1918 ++ .../services/network_security/pagers.py | 166 + .../network_security/transports/README.rst | 9 + .../network_security/transports/__init__.py | 38 + .../network_security/transports/base.py | 353 + .../network_security/transports/grpc.py | 664 + .../transports/grpc_asyncio.py | 750 + .../network_security/transports/rest.py | 2341 +++ .../network_security/transports/rest_base.py | 614 + .../types/__init__.py | 48 + .../types/client_tls_policy.py | 271 + .../network_security_v1alpha1/types/common.py | 95 + .../types/network_security.py | 26 + .../network_security_v1alpha1/types/tls.py | 197 + .../v1alpha1/mypy.ini | 3 + .../v1alpha1/noxfile.py | 592 + ...security_create_client_tls_policy_async.py | 61 + ..._security_create_client_tls_policy_sync.py | 61 + ...security_delete_client_tls_policy_async.py | 56 + ..._security_delete_client_tls_policy_sync.py | 56 + ...rk_security_get_client_tls_policy_async.py | 52 + ...ork_security_get_client_tls_policy_sync.py | 52 + ...security_list_client_tls_policies_async.py | 53 + ..._security_list_client_tls_policies_sync.py | 53 + ...security_update_client_tls_policy_async.py | 59 + ..._security_update_client_tls_policy_sync.py | 59 + ...google.cloud.networksecurity.v1alpha1.json | 844 + ...ixup_network_security_v1alpha1_keywords.py | 180 + .../v1alpha1/setup.py | 99 + .../v1alpha1/testing/constraints-3.10.txt | 7 + .../v1alpha1/testing/constraints-3.11.txt | 7 + .../v1alpha1/testing/constraints-3.12.txt | 7 + .../v1alpha1/testing/constraints-3.13.txt | 12 + .../v1alpha1/testing/constraints-3.7.txt | 11 + .../v1alpha1/testing/constraints-3.8.txt | 7 + .../v1alpha1/testing/constraints-3.9.txt | 7 + .../v1alpha1/tests/__init__.py | 16 + .../v1alpha1/tests/unit/__init__.py | 16 + .../v1alpha1/tests/unit/gapic/__init__.py | 16 + .../network_security_v1alpha1/__init__.py | 16 + .../test_network_security.py | 7023 ++++++++ .../v1beta1/.coveragerc | 13 + .../v1beta1/.flake8 | 34 + .../v1beta1/LICENSE | 202 + .../v1beta1/MANIFEST.in | 20 + .../v1beta1/README.rst | 143 + .../v1beta1/docs/_static/custom.css | 20 + .../v1beta1/docs/_templates/layout.html | 50 + .../v1beta1/docs/conf.py | 385 + .../v1beta1/docs/index.rst | 10 + .../v1beta1/docs/multiprocessing.rst | 7 + .../network_security.rst | 10 + .../network_security_v1beta1/services_.rst | 6 + .../docs/network_security_v1beta1/types_.rst | 6 + .../google/cloud/network_security/__init__.py | 79 + .../cloud/network_security/gapic_version.py | 16 + .../google/cloud/network_security/py.typed | 2 + .../network_security_v1beta1/__init__.py | 80 + .../gapic_metadata.json | 173 + .../network_security_v1beta1/gapic_version.py | 16 + .../cloud/network_security_v1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../services/network_security/__init__.py | 22 + .../services/network_security/async_client.py | 2866 +++ .../services/network_security/client.py | 3251 ++++ .../services/network_security/pagers.py | 446 + .../network_security/transports/README.rst | 9 + .../network_security/transports/__init__.py | 33 + .../network_security/transports/base.py | 497 + .../network_security/transports/grpc.py | 933 + .../transports/grpc_asyncio.py | 1069 ++ .../types/__init__.py | 80 + .../types/authorization_policy.py | 425 + .../types/client_tls_policy.py | 271 + .../network_security_v1beta1/types/common.py | 95 + .../types/network_security.py | 26 + .../types/server_tls_policy.py | 296 + .../network_security_v1beta1/types/tls.py | 154 + .../v1beta1/mypy.ini | 3 + .../v1beta1/noxfile.py | 592 + ...urity_create_authorization_policy_async.py | 62 + ...curity_create_authorization_policy_sync.py | 62 + ...security_create_client_tls_policy_async.py | 61 + ..._security_create_client_tls_policy_sync.py | 61 + ...security_create_server_tls_policy_async.py | 61 + ..._security_create_server_tls_policy_sync.py | 61 + ...urity_delete_authorization_policy_async.py | 56 + ...curity_delete_authorization_policy_sync.py | 56 + ...security_delete_client_tls_policy_async.py | 56 + ..._security_delete_client_tls_policy_sync.py | 56 + ...security_delete_server_tls_policy_async.py | 56 + ..._security_delete_server_tls_policy_sync.py | 56 + ...security_get_authorization_policy_async.py | 52 + ..._security_get_authorization_policy_sync.py | 52 + ...rk_security_get_client_tls_policy_async.py | 52 + ...ork_security_get_client_tls_policy_sync.py | 52 + ...rk_security_get_server_tls_policy_async.py | 52 + ...ork_security_get_server_tls_policy_sync.py | 52 + ...urity_list_authorization_policies_async.py | 53 + ...curity_list_authorization_policies_sync.py | 53 + ...security_list_client_tls_policies_async.py | 53 + ..._security_list_client_tls_policies_sync.py | 53 + ...security_list_server_tls_policies_async.py | 53 + ..._security_list_server_tls_policies_sync.py | 53 + ...urity_update_authorization_policy_async.py | 60 + ...curity_update_authorization_policy_sync.py | 60 + ...security_update_client_tls_policy_async.py | 59 + ..._security_update_client_tls_policy_sync.py | 59 + ...security_update_server_tls_policy_async.py | 59 + ..._security_update_server_tls_policy_sync.py | 59 + ..._google.cloud.networksecurity.v1beta1.json | 2502 +++ ...fixup_network_security_v1beta1_keywords.py | 190 + .../v1beta1/setup.py | 99 + .../v1beta1/testing/constraints-3.10.txt | 7 + .../v1beta1/testing/constraints-3.11.txt | 7 + .../v1beta1/testing/constraints-3.12.txt | 7 + .../v1beta1/testing/constraints-3.13.txt | 12 + .../v1beta1/testing/constraints-3.7.txt | 11 + .../v1beta1/testing/constraints-3.8.txt | 7 + .../v1beta1/testing/constraints-3.9.txt | 7 + .../v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../network_security_v1beta1/__init__.py | 16 + .../test_network_security.py | 8936 ++++++++++ 297 files changed, 129893 insertions(+) create mode 100644 owl-bot-staging/google-cloud-network-security/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-network-security/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-network-security/v1/LICENSE create mode 100644 owl-bot-staging/google-cloud-network-security/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-network-security/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/_templates/layout.html create mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/multiprocessing.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/address_group_service.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/network_security.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/organization_address_group_service.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/py.typed create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/client.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/async_client.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/client.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/pagers.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/base.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/client.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/address_group.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/authorization_policy.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/client_tls_policy.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/common.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/network_security.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/server_tls_policy.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/tls.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-network-security/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json create mode 100644 owl-bot-staging/google-cloud-network-security/v1/scripts/fixup_network_security_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_address_group_service.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_network_security.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/.flake8 create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/LICENSE create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/README.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_templates/layout.html create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/multiprocessing.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/network_security.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/services_.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/types_.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/py.typed create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/py.typed create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/async_client.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/client.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/pagers.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/base.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/client_tls_policy.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/common.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/network_security.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/tls.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/scripts/fixup_network_security_v1alpha1_keywords.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/setup.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/test_network_security.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/.flake8 create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/LICENSE create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/README.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/_templates/layout.html create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/multiprocessing.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/network_security.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/services_.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/types_.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/py.typed create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/py.typed create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/async_client.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/client.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/pagers.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/base.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/authorization_policy.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/client_tls_policy.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/common.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/network_security.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/server_tls_policy.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/tls.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/scripts/fixup_network_security_v1beta1_keywords.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/setup.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/__init__.py create mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/test_network_security.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/.coveragerc b/owl-bot-staging/google-cloud-network-security/v1/.coveragerc new file mode 100644 index 000000000000..ed01d62f0f9a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/network_security/__init__.py + google/cloud/network_security/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-network-security/v1/.flake8 b/owl-bot-staging/google-cloud-network-security/v1/.flake8 new file mode 100644 index 000000000000..90316de21489 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/.flake8 @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +[flake8] +# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): +# Resolve flake8 lint issues +ignore = E203, E231, E266, E501, W503 +exclude = + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): + # Ensure that generated code passes flake8 lint + **/gapic/** + **/services/** + **/types/** + # Exclude Protobuf gencode + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/LICENSE b/owl-bot-staging/google-cloud-network-security/v1/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT 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/google-cloud-network-security/v1/MANIFEST.in b/owl-bot-staging/google-cloud-network-security/v1/MANIFEST.in new file mode 100644 index 000000000000..dae249ec8976 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/MANIFEST.in @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +include README.rst LICENSE +recursive-include google *.py *.pyi *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ diff --git a/owl-bot-staging/google-cloud-network-security/v1/README.rst b/owl-bot-staging/google-cloud-network-security/v1/README.rst new file mode 100644 index 000000000000..fed4f0a4d3c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Cloud Network Security 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 Network Security 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 + + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + + +Examples +^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + + +Examples +^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-security/v1/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/_templates/layout.html b/owl-bot-staging/google-cloud-network-security/v1/docs/_templates/layout.html new file mode 100644 index 000000000000..95e9c77fcfe1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/conf.py b/owl-bot-staging/google-cloud-network-security/v1/docs/conf.py new file mode 100644 index 000000000000..cf26b0443b74 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/docs/conf.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-network-security 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("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.5.0" + +# 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.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-network-security" +copyright = u"2025, Google, LLC" +author = u"Google APIs" + +# 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", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# 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 google-cloud-network-security", + "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-network-security-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-network-security.tex", + u"google-cloud-network-security Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-network-security", + "google-cloud-network-security Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-network-security", + "google-cloud-network-security Documentation", + author, + "google-cloud-network-security", + "google-cloud-network-security Library", + "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": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", 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/google-cloud-network-security/v1/docs/index.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/index.rst new file mode 100644 index 000000000000..84467baeb84a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/docs/index.rst @@ -0,0 +1,10 @@ +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + network_security_v1/services_ + network_security_v1/types_ diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/multiprocessing.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/address_group_service.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/address_group_service.rst new file mode 100644 index 000000000000..3d7700eb2a76 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/address_group_service.rst @@ -0,0 +1,10 @@ +AddressGroupService +------------------------------------- + +.. automodule:: google.cloud.network_security_v1.services.address_group_service + :members: + :inherited-members: + +.. automodule:: google.cloud.network_security_v1.services.address_group_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/network_security.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/network_security.rst new file mode 100644 index 000000000000..aa99d3fc659b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/network_security.rst @@ -0,0 +1,10 @@ +NetworkSecurity +--------------------------------- + +.. automodule:: google.cloud.network_security_v1.services.network_security + :members: + :inherited-members: + +.. automodule:: google.cloud.network_security_v1.services.network_security.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/organization_address_group_service.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/organization_address_group_service.rst new file mode 100644 index 000000000000..854cf25a9cdb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/organization_address_group_service.rst @@ -0,0 +1,10 @@ +OrganizationAddressGroupService +------------------------------------------------- + +.. automodule:: google.cloud.network_security_v1.services.organization_address_group_service + :members: + :inherited-members: + +.. automodule:: google.cloud.network_security_v1.services.organization_address_group_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/services_.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/services_.rst new file mode 100644 index 000000000000..a78574643ed1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/services_.rst @@ -0,0 +1,8 @@ +Services for Google Cloud Network Security v1 API +================================================= +.. toctree:: + :maxdepth: 2 + + address_group_service + network_security + organization_address_group_service diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/types_.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/types_.rst new file mode 100644 index 000000000000..61c840bc8d6f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Network Security v1 API +============================================== + +.. automodule:: google.cloud.network_security_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/__init__.py new file mode 100644 index 000000000000..4b235ebcb40e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/__init__.py @@ -0,0 +1,111 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.network_security import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.network_security_v1.services.address_group_service.client import AddressGroupServiceClient +from google.cloud.network_security_v1.services.address_group_service.async_client import AddressGroupServiceAsyncClient +from google.cloud.network_security_v1.services.network_security.client import NetworkSecurityClient +from google.cloud.network_security_v1.services.network_security.async_client import NetworkSecurityAsyncClient +from google.cloud.network_security_v1.services.organization_address_group_service.client import OrganizationAddressGroupServiceClient +from google.cloud.network_security_v1.services.organization_address_group_service.async_client import OrganizationAddressGroupServiceAsyncClient + +from google.cloud.network_security_v1.types.address_group import AddAddressGroupItemsRequest +from google.cloud.network_security_v1.types.address_group import AddressGroup +from google.cloud.network_security_v1.types.address_group import CloneAddressGroupItemsRequest +from google.cloud.network_security_v1.types.address_group import CreateAddressGroupRequest +from google.cloud.network_security_v1.types.address_group import DeleteAddressGroupRequest +from google.cloud.network_security_v1.types.address_group import GetAddressGroupRequest +from google.cloud.network_security_v1.types.address_group import ListAddressGroupReferencesRequest +from google.cloud.network_security_v1.types.address_group import ListAddressGroupReferencesResponse +from google.cloud.network_security_v1.types.address_group import ListAddressGroupsRequest +from google.cloud.network_security_v1.types.address_group import ListAddressGroupsResponse +from google.cloud.network_security_v1.types.address_group import RemoveAddressGroupItemsRequest +from google.cloud.network_security_v1.types.address_group import UpdateAddressGroupRequest +from google.cloud.network_security_v1.types.authorization_policy import AuthorizationPolicy +from google.cloud.network_security_v1.types.authorization_policy import CreateAuthorizationPolicyRequest +from google.cloud.network_security_v1.types.authorization_policy import DeleteAuthorizationPolicyRequest +from google.cloud.network_security_v1.types.authorization_policy import GetAuthorizationPolicyRequest +from google.cloud.network_security_v1.types.authorization_policy import ListAuthorizationPoliciesRequest +from google.cloud.network_security_v1.types.authorization_policy import ListAuthorizationPoliciesResponse +from google.cloud.network_security_v1.types.authorization_policy import UpdateAuthorizationPolicyRequest +from google.cloud.network_security_v1.types.client_tls_policy import ClientTlsPolicy +from google.cloud.network_security_v1.types.client_tls_policy import CreateClientTlsPolicyRequest +from google.cloud.network_security_v1.types.client_tls_policy import DeleteClientTlsPolicyRequest +from google.cloud.network_security_v1.types.client_tls_policy import GetClientTlsPolicyRequest +from google.cloud.network_security_v1.types.client_tls_policy import ListClientTlsPoliciesRequest +from google.cloud.network_security_v1.types.client_tls_policy import ListClientTlsPoliciesResponse +from google.cloud.network_security_v1.types.client_tls_policy import UpdateClientTlsPolicyRequest +from google.cloud.network_security_v1.types.common import OperationMetadata +from google.cloud.network_security_v1.types.server_tls_policy import CreateServerTlsPolicyRequest +from google.cloud.network_security_v1.types.server_tls_policy import DeleteServerTlsPolicyRequest +from google.cloud.network_security_v1.types.server_tls_policy import GetServerTlsPolicyRequest +from google.cloud.network_security_v1.types.server_tls_policy import ListServerTlsPoliciesRequest +from google.cloud.network_security_v1.types.server_tls_policy import ListServerTlsPoliciesResponse +from google.cloud.network_security_v1.types.server_tls_policy import ServerTlsPolicy +from google.cloud.network_security_v1.types.server_tls_policy import UpdateServerTlsPolicyRequest +from google.cloud.network_security_v1.types.tls import CertificateProvider +from google.cloud.network_security_v1.types.tls import CertificateProviderInstance +from google.cloud.network_security_v1.types.tls import GrpcEndpoint +from google.cloud.network_security_v1.types.tls import ValidationCA + +__all__ = ('AddressGroupServiceClient', + 'AddressGroupServiceAsyncClient', + 'NetworkSecurityClient', + 'NetworkSecurityAsyncClient', + 'OrganizationAddressGroupServiceClient', + 'OrganizationAddressGroupServiceAsyncClient', + 'AddAddressGroupItemsRequest', + 'AddressGroup', + 'CloneAddressGroupItemsRequest', + 'CreateAddressGroupRequest', + 'DeleteAddressGroupRequest', + 'GetAddressGroupRequest', + 'ListAddressGroupReferencesRequest', + 'ListAddressGroupReferencesResponse', + 'ListAddressGroupsRequest', + 'ListAddressGroupsResponse', + 'RemoveAddressGroupItemsRequest', + 'UpdateAddressGroupRequest', + 'AuthorizationPolicy', + 'CreateAuthorizationPolicyRequest', + 'DeleteAuthorizationPolicyRequest', + 'GetAuthorizationPolicyRequest', + 'ListAuthorizationPoliciesRequest', + 'ListAuthorizationPoliciesResponse', + 'UpdateAuthorizationPolicyRequest', + 'ClientTlsPolicy', + 'CreateClientTlsPolicyRequest', + 'DeleteClientTlsPolicyRequest', + 'GetClientTlsPolicyRequest', + 'ListClientTlsPoliciesRequest', + 'ListClientTlsPoliciesResponse', + 'UpdateClientTlsPolicyRequest', + 'OperationMetadata', + 'CreateServerTlsPolicyRequest', + 'DeleteServerTlsPolicyRequest', + 'GetServerTlsPolicyRequest', + 'ListServerTlsPoliciesRequest', + 'ListServerTlsPoliciesResponse', + 'ServerTlsPolicy', + 'UpdateServerTlsPolicyRequest', + 'CertificateProvider', + 'CertificateProviderInstance', + 'GrpcEndpoint', + 'ValidationCA', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/py.typed b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/py.typed new file mode 100644 index 000000000000..41b3c3019247 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/__init__.py new file mode 100644 index 000000000000..64b6f78340a7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/__init__.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.network_security_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.address_group_service import AddressGroupServiceClient +from .services.address_group_service import AddressGroupServiceAsyncClient +from .services.network_security import NetworkSecurityClient +from .services.network_security import NetworkSecurityAsyncClient +from .services.organization_address_group_service import OrganizationAddressGroupServiceClient +from .services.organization_address_group_service import OrganizationAddressGroupServiceAsyncClient + +from .types.address_group import AddAddressGroupItemsRequest +from .types.address_group import AddressGroup +from .types.address_group import CloneAddressGroupItemsRequest +from .types.address_group import CreateAddressGroupRequest +from .types.address_group import DeleteAddressGroupRequest +from .types.address_group import GetAddressGroupRequest +from .types.address_group import ListAddressGroupReferencesRequest +from .types.address_group import ListAddressGroupReferencesResponse +from .types.address_group import ListAddressGroupsRequest +from .types.address_group import ListAddressGroupsResponse +from .types.address_group import RemoveAddressGroupItemsRequest +from .types.address_group import UpdateAddressGroupRequest +from .types.authorization_policy import AuthorizationPolicy +from .types.authorization_policy import CreateAuthorizationPolicyRequest +from .types.authorization_policy import DeleteAuthorizationPolicyRequest +from .types.authorization_policy import GetAuthorizationPolicyRequest +from .types.authorization_policy import ListAuthorizationPoliciesRequest +from .types.authorization_policy import ListAuthorizationPoliciesResponse +from .types.authorization_policy import UpdateAuthorizationPolicyRequest +from .types.client_tls_policy import ClientTlsPolicy +from .types.client_tls_policy import CreateClientTlsPolicyRequest +from .types.client_tls_policy import DeleteClientTlsPolicyRequest +from .types.client_tls_policy import GetClientTlsPolicyRequest +from .types.client_tls_policy import ListClientTlsPoliciesRequest +from .types.client_tls_policy import ListClientTlsPoliciesResponse +from .types.client_tls_policy import UpdateClientTlsPolicyRequest +from .types.common import OperationMetadata +from .types.server_tls_policy import CreateServerTlsPolicyRequest +from .types.server_tls_policy import DeleteServerTlsPolicyRequest +from .types.server_tls_policy import GetServerTlsPolicyRequest +from .types.server_tls_policy import ListServerTlsPoliciesRequest +from .types.server_tls_policy import ListServerTlsPoliciesResponse +from .types.server_tls_policy import ServerTlsPolicy +from .types.server_tls_policy import UpdateServerTlsPolicyRequest +from .types.tls import CertificateProvider +from .types.tls import CertificateProviderInstance +from .types.tls import GrpcEndpoint +from .types.tls import ValidationCA + +__all__ = ( + 'AddressGroupServiceAsyncClient', + 'NetworkSecurityAsyncClient', + 'OrganizationAddressGroupServiceAsyncClient', +'AddAddressGroupItemsRequest', +'AddressGroup', +'AddressGroupServiceClient', +'AuthorizationPolicy', +'CertificateProvider', +'CertificateProviderInstance', +'ClientTlsPolicy', +'CloneAddressGroupItemsRequest', +'CreateAddressGroupRequest', +'CreateAuthorizationPolicyRequest', +'CreateClientTlsPolicyRequest', +'CreateServerTlsPolicyRequest', +'DeleteAddressGroupRequest', +'DeleteAuthorizationPolicyRequest', +'DeleteClientTlsPolicyRequest', +'DeleteServerTlsPolicyRequest', +'GetAddressGroupRequest', +'GetAuthorizationPolicyRequest', +'GetClientTlsPolicyRequest', +'GetServerTlsPolicyRequest', +'GrpcEndpoint', +'ListAddressGroupReferencesRequest', +'ListAddressGroupReferencesResponse', +'ListAddressGroupsRequest', +'ListAddressGroupsResponse', +'ListAuthorizationPoliciesRequest', +'ListAuthorizationPoliciesResponse', +'ListClientTlsPoliciesRequest', +'ListClientTlsPoliciesResponse', +'ListServerTlsPoliciesRequest', +'ListServerTlsPoliciesResponse', +'NetworkSecurityClient', +'OperationMetadata', +'OrganizationAddressGroupServiceClient', +'RemoveAddressGroupItemsRequest', +'ServerTlsPolicy', +'UpdateAddressGroupRequest', +'UpdateAuthorizationPolicyRequest', +'UpdateClientTlsPolicyRequest', +'UpdateServerTlsPolicyRequest', +'ValidationCA', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_metadata.json new file mode 100644 index 000000000000..7a369b0303ca --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_metadata.json @@ -0,0 +1,561 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.network_security_v1", + "protoPackage": "google.cloud.networksecurity.v1", + "schema": "1.0", + "services": { + "AddressGroupService": { + "clients": { + "grpc": { + "libraryClient": "AddressGroupServiceClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AddressGroupServiceAsyncClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + }, + "rest": { + "libraryClient": "AddressGroupServiceClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + } + } + }, + "NetworkSecurity": { + "clients": { + "grpc": { + "libraryClient": "NetworkSecurityClient", + "rpcs": { + "CreateAuthorizationPolicy": { + "methods": [ + "create_authorization_policy" + ] + }, + "CreateClientTlsPolicy": { + "methods": [ + "create_client_tls_policy" + ] + }, + "CreateServerTlsPolicy": { + "methods": [ + "create_server_tls_policy" + ] + }, + "DeleteAuthorizationPolicy": { + "methods": [ + "delete_authorization_policy" + ] + }, + "DeleteClientTlsPolicy": { + "methods": [ + "delete_client_tls_policy" + ] + }, + "DeleteServerTlsPolicy": { + "methods": [ + "delete_server_tls_policy" + ] + }, + "GetAuthorizationPolicy": { + "methods": [ + "get_authorization_policy" + ] + }, + "GetClientTlsPolicy": { + "methods": [ + "get_client_tls_policy" + ] + }, + "GetServerTlsPolicy": { + "methods": [ + "get_server_tls_policy" + ] + }, + "ListAuthorizationPolicies": { + "methods": [ + "list_authorization_policies" + ] + }, + "ListClientTlsPolicies": { + "methods": [ + "list_client_tls_policies" + ] + }, + "ListServerTlsPolicies": { + "methods": [ + "list_server_tls_policies" + ] + }, + "UpdateAuthorizationPolicy": { + "methods": [ + "update_authorization_policy" + ] + }, + "UpdateClientTlsPolicy": { + "methods": [ + "update_client_tls_policy" + ] + }, + "UpdateServerTlsPolicy": { + "methods": [ + "update_server_tls_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "NetworkSecurityAsyncClient", + "rpcs": { + "CreateAuthorizationPolicy": { + "methods": [ + "create_authorization_policy" + ] + }, + "CreateClientTlsPolicy": { + "methods": [ + "create_client_tls_policy" + ] + }, + "CreateServerTlsPolicy": { + "methods": [ + "create_server_tls_policy" + ] + }, + "DeleteAuthorizationPolicy": { + "methods": [ + "delete_authorization_policy" + ] + }, + "DeleteClientTlsPolicy": { + "methods": [ + "delete_client_tls_policy" + ] + }, + "DeleteServerTlsPolicy": { + "methods": [ + "delete_server_tls_policy" + ] + }, + "GetAuthorizationPolicy": { + "methods": [ + "get_authorization_policy" + ] + }, + "GetClientTlsPolicy": { + "methods": [ + "get_client_tls_policy" + ] + }, + "GetServerTlsPolicy": { + "methods": [ + "get_server_tls_policy" + ] + }, + "ListAuthorizationPolicies": { + "methods": [ + "list_authorization_policies" + ] + }, + "ListClientTlsPolicies": { + "methods": [ + "list_client_tls_policies" + ] + }, + "ListServerTlsPolicies": { + "methods": [ + "list_server_tls_policies" + ] + }, + "UpdateAuthorizationPolicy": { + "methods": [ + "update_authorization_policy" + ] + }, + "UpdateClientTlsPolicy": { + "methods": [ + "update_client_tls_policy" + ] + }, + "UpdateServerTlsPolicy": { + "methods": [ + "update_server_tls_policy" + ] + } + } + }, + "rest": { + "libraryClient": "NetworkSecurityClient", + "rpcs": { + "CreateAuthorizationPolicy": { + "methods": [ + "create_authorization_policy" + ] + }, + "CreateClientTlsPolicy": { + "methods": [ + "create_client_tls_policy" + ] + }, + "CreateServerTlsPolicy": { + "methods": [ + "create_server_tls_policy" + ] + }, + "DeleteAuthorizationPolicy": { + "methods": [ + "delete_authorization_policy" + ] + }, + "DeleteClientTlsPolicy": { + "methods": [ + "delete_client_tls_policy" + ] + }, + "DeleteServerTlsPolicy": { + "methods": [ + "delete_server_tls_policy" + ] + }, + "GetAuthorizationPolicy": { + "methods": [ + "get_authorization_policy" + ] + }, + "GetClientTlsPolicy": { + "methods": [ + "get_client_tls_policy" + ] + }, + "GetServerTlsPolicy": { + "methods": [ + "get_server_tls_policy" + ] + }, + "ListAuthorizationPolicies": { + "methods": [ + "list_authorization_policies" + ] + }, + "ListClientTlsPolicies": { + "methods": [ + "list_client_tls_policies" + ] + }, + "ListServerTlsPolicies": { + "methods": [ + "list_server_tls_policies" + ] + }, + "UpdateAuthorizationPolicy": { + "methods": [ + "update_authorization_policy" + ] + }, + "UpdateClientTlsPolicy": { + "methods": [ + "update_client_tls_policy" + ] + }, + "UpdateServerTlsPolicy": { + "methods": [ + "update_server_tls_policy" + ] + } + } + } + } + }, + "OrganizationAddressGroupService": { + "clients": { + "grpc": { + "libraryClient": "OrganizationAddressGroupServiceClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OrganizationAddressGroupServiceAsyncClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + }, + "rest": { + "libraryClient": "OrganizationAddressGroupServiceClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/py.typed b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/py.typed new file mode 100644 index 000000000000..41b3c3019247 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/__init__.py new file mode 100644 index 000000000000..f100e3c88e55 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 AddressGroupServiceClient +from .async_client import AddressGroupServiceAsyncClient + +__all__ = ( + 'AddressGroupServiceClient', + 'AddressGroupServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/async_client.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/async_client.py new file mode 100644 index 000000000000..163edd248829 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/async_client.py @@ -0,0 +1,2047 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.network_security_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.services.address_group_service import pagers +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import common +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AddressGroupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AddressGroupServiceGrpcAsyncIOTransport +from .client import AddressGroupServiceClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class AddressGroupServiceAsyncClient: + """AddressGroup is a resource that manages a collection of IP or + Domain Names, it can be used in Firewall Policy to represent + allow or deny traffic from all the IP or Domain Names from the + Address Group. + """ + + _client: AddressGroupServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AddressGroupServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AddressGroupServiceClient._DEFAULT_UNIVERSE + + address_group_path = staticmethod(AddressGroupServiceClient.address_group_path) + parse_address_group_path = staticmethod(AddressGroupServiceClient.parse_address_group_path) + common_billing_account_path = staticmethod(AddressGroupServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AddressGroupServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AddressGroupServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AddressGroupServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AddressGroupServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AddressGroupServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AddressGroupServiceClient.common_project_path) + parse_common_project_path = staticmethod(AddressGroupServiceClient.parse_common_project_path) + common_location_path = staticmethod(AddressGroupServiceClient.common_location_path) + parse_common_location_path = staticmethod(AddressGroupServiceClient.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: + AddressGroupServiceAsyncClient: The constructed client. + """ + return AddressGroupServiceClient.from_service_account_info.__func__(AddressGroupServiceAsyncClient, 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: + AddressGroupServiceAsyncClient: The constructed client. + """ + return AddressGroupServiceClient.from_service_account_file.__func__(AddressGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return AddressGroupServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AddressGroupServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AddressGroupServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = AddressGroupServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AddressGroupServiceTransport, Callable[..., AddressGroupServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the address group service async 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 (Optional[Union[str,AddressGroupServiceTransport,Callable[..., AddressGroupServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AddressGroupServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = AddressGroupServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient`.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "credentialsType": None, + } + ) + + async def list_address_groups(self, + request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupsAsyncPager: + r"""Lists address groups in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_address_groups(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_address_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListAddressGroupsRequest, dict]]): + The request object. Request used with the + ListAddressGroups method. + parent (:class:`str`): + Required. The project and location from which the + AddressGroups should be listed, specified in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupsAsyncPager: + Response returned by the + ListAddressGroups method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.ListAddressGroupsRequest): + request = address_group.ListAddressGroupsRequest(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._client._transport._wrapped_methods[self._client._transport.list_address_groups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAddressGroupsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_address_group(self, + request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.AddressGroup: + r"""Gets details of a single address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_get_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetAddressGroupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_address_group(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetAddressGroupRequest, dict]]): + The request object. Request used by the GetAddressGroup + method. + name (:class:`str`): + Required. A name of the AddressGroup to get. Must be in + the format + ``projects/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.types.AddressGroup: + AddressGroup is a resource that + specifies how a collection of IP/DNS + used in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.GetAddressGroupRequest): + request = address_group.GetAddressGroupRequest(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._client._transport._wrapped_methods[self._client._transport.get_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_address_group(self, + request: Optional[Union[gcn_address_group.CreateAddressGroupRequest, dict]] = None, + *, + parent: Optional[str] = None, + address_group: Optional[gcn_address_group.AddressGroup] = None, + address_group_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new address group in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_create_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.CreateAddressGroupRequest( + parent="parent_value", + address_group_id="address_group_id_value", + address_group=address_group, + ) + + # Make the request + operation = client.create_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateAddressGroupRequest, dict]]): + The request object. Request used by the + CreateAddressGroup method. + parent (:class:`str`): + Required. The parent resource of the AddressGroup. Must + be in the format ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + address_group (:class:`google.cloud.network_security_v1.types.AddressGroup`): + Required. AddressGroup resource to be + created. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + address_group_id (:class:`str`): + Required. Short name of the AddressGroup resource to be + created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "authz_policy". + + This corresponds to the ``address_group_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, address_group, address_group_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.CreateAddressGroupRequest): + request = gcn_address_group.CreateAddressGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if address_group is not None: + request.address_group = address_group + if address_group_id is not None: + request.address_group_id = address_group_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_address_group] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_address_group(self, + request: Optional[Union[gcn_address_group.UpdateAddressGroupRequest, dict]] = None, + *, + address_group: Optional[gcn_address_group.AddressGroup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_update_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.UpdateAddressGroupRequest( + address_group=address_group, + ) + + # Make the request + operation = client.update_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.UpdateAddressGroupRequest, dict]]): + The request object. Request used by the + UpdateAddressGroup method. + address_group (:class:`google.cloud.network_security_v1.types.AddressGroup`): + Required. Updated AddressGroup + resource. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the AddressGroup resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.UpdateAddressGroupRequest): + request = gcn_address_group.UpdateAddressGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group.name", request.address_group.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def add_address_group_items(self, + request: Optional[Union[gcn_address_group.AddAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Adds items to an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_add_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.AddAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.add_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.AddAddressGroupItemsRequest, dict]]): + The request object. Request used by the + AddAddressGroupItems method. + address_group (:class:`str`): + Required. A name of the AddressGroup to add items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + items (:class:`MutableSequence[str]`): + Required. List of items to add. + This corresponds to the ``items`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, items] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.AddAddressGroupItemsRequest): + request = gcn_address_group.AddAddressGroupItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if items: + request.items.extend(items) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.add_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def remove_address_group_items(self, + request: Optional[Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Removes items from an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_remove_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.RemoveAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.remove_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest, dict]]): + The request object. Request used by the + RemoveAddressGroupItems method. + address_group (:class:`str`): + Required. A name of the AddressGroup to remove items + from. Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + items (:class:`MutableSequence[str]`): + Required. List of items to remove. + This corresponds to the ``items`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, items] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.RemoveAddressGroupItemsRequest): + request = gcn_address_group.RemoveAddressGroupItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if items: + request.items.extend(items) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.remove_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def clone_address_group_items(self, + request: Optional[Union[gcn_address_group.CloneAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + source_address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Clones items from one address group to another. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_clone_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CloneAddressGroupItemsRequest( + address_group="address_group_value", + source_address_group="source_address_group_value", + ) + + # Make the request + operation = client.clone_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest, dict]]): + The request object. Request used by the + CloneAddressGroupItems method. + address_group (:class:`str`): + Required. A name of the AddressGroup to clone items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source_address_group (:class:`str`): + Required. Source address group to + clone items from. + + This corresponds to the ``source_address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, source_address_group] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.CloneAddressGroupItemsRequest): + request = gcn_address_group.CloneAddressGroupItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if source_address_group is not None: + request.source_address_group = source_address_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.clone_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_address_group(self, + request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_delete_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAddressGroupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.DeleteAddressGroupRequest, dict]]): + The request object. Request used by the + DeleteAddressGroup method. + name (:class:`str`): + Required. A name of the AddressGroup to delete. Must be + in the format + ``projects/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.DeleteAddressGroupRequest): + request = address_group.DeleteAddressGroupRequest(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._client._transport._wrapped_methods[self._client._transport.delete_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_address_group_references(self, + request: Optional[Union[gcn_address_group.ListAddressGroupReferencesRequest, dict]] = None, + *, + address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupReferencesAsyncPager: + r"""Lists references of an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_address_group_references(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupReferencesRequest( + address_group="address_group_value", + ) + + # Make the request + page_result = client.list_address_group_references(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest, dict]]): + The request object. Request used by the + ListAddressGroupReferences method. + address_group (:class:`str`): + Required. A name of the AddressGroup to clone items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupReferencesAsyncPager: + Response of the + ListAddressGroupReferences method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.ListAddressGroupReferencesRequest): + request = gcn_address_group.ListAddressGroupReferencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_address_group_references] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAddressGroupReferencesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AddressGroupServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "AddressGroupServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/client.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/client.py new file mode 100644 index 000000000000..a99a24c5547f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/client.py @@ -0,0 +1,2422 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.network_security_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.services.address_group_service import pagers +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import common +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import AddressGroupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AddressGroupServiceGrpcTransport +from .transports.grpc_asyncio import AddressGroupServiceGrpcAsyncIOTransport +from .transports.rest import AddressGroupServiceRestTransport + + +class AddressGroupServiceClientMeta(type): + """Metaclass for the AddressGroupService 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[AddressGroupServiceTransport]] + _transport_registry["grpc"] = AddressGroupServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AddressGroupServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AddressGroupServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AddressGroupServiceTransport]: + """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 AddressGroupServiceClient(metaclass=AddressGroupServiceClientMeta): + """AddressGroup is a resource that manages a collection of IP or + Domain Names, it can be used in Firewall Policy to represent + allow or deny traffic from all the IP or Domain Names from the + Address Group. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "networksecurity.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networksecurity.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + AddressGroupServiceClient: 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: + AddressGroupServiceClient: 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) -> AddressGroupServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AddressGroupServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def address_group_path(project: str,location: str,address_group: str,) -> str: + """Returns a fully-qualified address_group string.""" + return "projects/{project}/locations/{location}/addressGroups/{address_group}".format(project=project, location=location, address_group=address_group, ) + + @staticmethod + def parse_address_group_path(path: str) -> Dict[str,str]: + """Parses a address_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/addressGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = AddressGroupServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AddressGroupServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AddressGroupServiceTransport, Callable[..., AddressGroupServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the address group 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 (Optional[Union[str,AddressGroupServiceTransport,Callable[..., AddressGroupServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AddressGroupServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AddressGroupServiceClient._read_environment_variables() + self._client_cert_source = AddressGroupServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AddressGroupServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AddressGroupServiceTransport) + if transport_provided: + # transport is a AddressGroupServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(AddressGroupServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AddressGroupServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[AddressGroupServiceTransport], Callable[..., AddressGroupServiceTransport]] = ( + AddressGroupServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AddressGroupServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networksecurity_v1.AddressGroupServiceClient`.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "credentialsType": None, + } + ) + + def list_address_groups(self, + request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupsPager: + r"""Lists address groups in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_address_groups(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_address_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListAddressGroupsRequest, dict]): + The request object. Request used with the + ListAddressGroups method. + parent (str): + Required. The project and location from which the + AddressGroups should be listed, specified in the format + ``projects/*/locations/{location}``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupsPager: + Response returned by the + ListAddressGroups method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.ListAddressGroupsRequest): + request = address_group.ListAddressGroupsRequest(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_address_groups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAddressGroupsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_address_group(self, + request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.AddressGroup: + r"""Gets details of a single address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_get_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetAddressGroupRequest( + name="name_value", + ) + + # Make the request + response = client.get_address_group(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetAddressGroupRequest, dict]): + The request object. Request used by the GetAddressGroup + method. + name (str): + Required. A name of the AddressGroup to get. Must be in + the format + ``projects/*/locations/{location}/addressGroups/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.types.AddressGroup: + AddressGroup is a resource that + specifies how a collection of IP/DNS + used in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.GetAddressGroupRequest): + request = address_group.GetAddressGroupRequest(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_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_address_group(self, + request: Optional[Union[gcn_address_group.CreateAddressGroupRequest, dict]] = None, + *, + parent: Optional[str] = None, + address_group: Optional[gcn_address_group.AddressGroup] = None, + address_group_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new address group in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_create_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.CreateAddressGroupRequest( + parent="parent_value", + address_group_id="address_group_id_value", + address_group=address_group, + ) + + # Make the request + operation = client.create_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateAddressGroupRequest, dict]): + The request object. Request used by the + CreateAddressGroup method. + parent (str): + Required. The parent resource of the AddressGroup. Must + be in the format ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + address_group (google.cloud.network_security_v1.types.AddressGroup): + Required. AddressGroup resource to be + created. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + address_group_id (str): + Required. Short name of the AddressGroup resource to be + created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "authz_policy". + + This corresponds to the ``address_group_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, address_group, address_group_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.CreateAddressGroupRequest): + request = gcn_address_group.CreateAddressGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if address_group is not None: + request.address_group = address_group + if address_group_id is not None: + request.address_group_id = address_group_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_address_group] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_address_group(self, + request: Optional[Union[gcn_address_group.UpdateAddressGroupRequest, dict]] = None, + *, + address_group: Optional[gcn_address_group.AddressGroup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_update_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.UpdateAddressGroupRequest( + address_group=address_group, + ) + + # Make the request + operation = client.update_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.UpdateAddressGroupRequest, dict]): + The request object. Request used by the + UpdateAddressGroup method. + address_group (google.cloud.network_security_v1.types.AddressGroup): + Required. Updated AddressGroup + resource. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the AddressGroup resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.UpdateAddressGroupRequest): + request = gcn_address_group.UpdateAddressGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group.name", request.address_group.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def add_address_group_items(self, + request: Optional[Union[gcn_address_group.AddAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Adds items to an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_add_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.AddAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.add_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.AddAddressGroupItemsRequest, dict]): + The request object. Request used by the + AddAddressGroupItems method. + address_group (str): + Required. A name of the AddressGroup to add items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + items (MutableSequence[str]): + Required. List of items to add. + This corresponds to the ``items`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, items] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.AddAddressGroupItemsRequest): + request = gcn_address_group.AddAddressGroupItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if items is not None: + request.items = items + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def remove_address_group_items(self, + request: Optional[Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Removes items from an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_remove_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.RemoveAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.remove_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest, dict]): + The request object. Request used by the + RemoveAddressGroupItems method. + address_group (str): + Required. A name of the AddressGroup to remove items + from. Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + items (MutableSequence[str]): + Required. List of items to remove. + This corresponds to the ``items`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, items] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.RemoveAddressGroupItemsRequest): + request = gcn_address_group.RemoveAddressGroupItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if items is not None: + request.items = items + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def clone_address_group_items(self, + request: Optional[Union[gcn_address_group.CloneAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + source_address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Clones items from one address group to another. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_clone_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.CloneAddressGroupItemsRequest( + address_group="address_group_value", + source_address_group="source_address_group_value", + ) + + # Make the request + operation = client.clone_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest, dict]): + The request object. Request used by the + CloneAddressGroupItems method. + address_group (str): + Required. A name of the AddressGroup to clone items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source_address_group (str): + Required. Source address group to + clone items from. + + This corresponds to the ``source_address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, source_address_group] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.CloneAddressGroupItemsRequest): + request = gcn_address_group.CloneAddressGroupItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if source_address_group is not None: + request.source_address_group = source_address_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.clone_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_address_group(self, + request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_delete_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAddressGroupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.DeleteAddressGroupRequest, dict]): + The request object. Request used by the + DeleteAddressGroup method. + name (str): + Required. A name of the AddressGroup to delete. Must be + in the format + ``projects/*/locations/{location}/addressGroups/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.DeleteAddressGroupRequest): + request = address_group.DeleteAddressGroupRequest(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_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_address_group_references(self, + request: Optional[Union[gcn_address_group.ListAddressGroupReferencesRequest, dict]] = None, + *, + address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupReferencesPager: + r"""Lists references of an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_address_group_references(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupReferencesRequest( + address_group="address_group_value", + ) + + # Make the request + page_result = client.list_address_group_references(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest, dict]): + The request object. Request used by the + ListAddressGroupReferences method. + address_group (str): + Required. A name of the AddressGroup to clone items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupReferencesPager: + Response of the + ListAddressGroupReferences method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.ListAddressGroupReferencesRequest): + request = gcn_address_group.ListAddressGroupReferencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_address_group_references] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAddressGroupReferencesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AddressGroupServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "AddressGroupServiceClient", +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/pagers.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/pagers.py new file mode 100644 index 000000000000..4c8ac9f092ff --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/pagers.py @@ -0,0 +1,306 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group + + +class ListAddressGroupsPager: + """A pager for iterating through ``list_address_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListAddressGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``address_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAddressGroups`` requests and continue to iterate + through the ``address_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListAddressGroupsResponse` + 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[..., address_group.ListAddressGroupsResponse], + request: address_group.ListAddressGroupsRequest, + response: address_group.ListAddressGroupsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListAddressGroupsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListAddressGroupsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = address_group.ListAddressGroupsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[address_group.ListAddressGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[address_group.AddressGroup]: + for page in self.pages: + yield from page.address_groups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAddressGroupsAsyncPager: + """A pager for iterating through ``list_address_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListAddressGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``address_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAddressGroups`` requests and continue to iterate + through the ``address_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListAddressGroupsResponse` + 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[address_group.ListAddressGroupsResponse]], + request: address_group.ListAddressGroupsRequest, + response: address_group.ListAddressGroupsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListAddressGroupsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListAddressGroupsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = address_group.ListAddressGroupsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[address_group.ListAddressGroupsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[address_group.AddressGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.address_groups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAddressGroupReferencesPager: + """A pager for iterating through ``list_address_group_references`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``address_group_references`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAddressGroupReferences`` requests and continue to iterate + through the ``address_group_references`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse` + 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[..., gcn_address_group.ListAddressGroupReferencesResponse], + request: gcn_address_group.ListAddressGroupReferencesRequest, + response: gcn_address_group.ListAddressGroupReferencesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = gcn_address_group.ListAddressGroupReferencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[gcn_address_group.ListAddressGroupReferencesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference]: + for page in self.pages: + yield from page.address_group_references + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAddressGroupReferencesAsyncPager: + """A pager for iterating through ``list_address_group_references`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``address_group_references`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAddressGroupReferences`` requests and continue to iterate + through the ``address_group_references`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse` + 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[gcn_address_group.ListAddressGroupReferencesResponse]], + request: gcn_address_group.ListAddressGroupReferencesRequest, + response: gcn_address_group.ListAddressGroupReferencesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = gcn_address_group.ListAddressGroupReferencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[gcn_address_group.ListAddressGroupReferencesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference]: + async def async_generator(): + async for page in self.pages: + for response in page.address_group_references: + 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/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/README.rst b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/README.rst new file mode 100644 index 000000000000..ca87b34ca26d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AddressGroupServiceTransport` is the ABC for all transports. +- public child `AddressGroupServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AddressGroupServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAddressGroupServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AddressGroupServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py new file mode 100644 index 000000000000..cea017c338fc --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 AddressGroupServiceTransport +from .grpc import AddressGroupServiceGrpcTransport +from .grpc_asyncio import AddressGroupServiceGrpcAsyncIOTransport +from .rest import AddressGroupServiceRestTransport +from .rest import AddressGroupServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AddressGroupServiceTransport]] +_transport_registry['grpc'] = AddressGroupServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AddressGroupServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AddressGroupServiceRestTransport + +__all__ = ( + 'AddressGroupServiceTransport', + 'AddressGroupServiceGrpcTransport', + 'AddressGroupServiceGrpcAsyncIOTransport', + 'AddressGroupServiceRestTransport', + 'AddressGroupServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/base.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/base.py new file mode 100644 index 000000000000..3a965a8989b9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/base.py @@ -0,0 +1,409 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.network_security_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AddressGroupServiceTransport(abc.ABC): + """Abstract transport class for AddressGroupService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'networksecurity.googleapis.com' + + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_address_groups: gapic_v1.method.wrap_method( + self.list_address_groups, + default_timeout=None, + client_info=client_info, + ), + self.get_address_group: gapic_v1.method.wrap_method( + self.get_address_group, + default_timeout=None, + client_info=client_info, + ), + self.create_address_group: gapic_v1.method.wrap_method( + self.create_address_group, + default_timeout=None, + client_info=client_info, + ), + self.update_address_group: gapic_v1.method.wrap_method( + self.update_address_group, + default_timeout=None, + client_info=client_info, + ), + self.add_address_group_items: gapic_v1.method.wrap_method( + self.add_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.remove_address_group_items: gapic_v1.method.wrap_method( + self.remove_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.clone_address_group_items: gapic_v1.method.wrap_method( + self.clone_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.delete_address_group: gapic_v1.method.wrap_method( + self.delete_address_group, + default_timeout=None, + client_info=client_info, + ), + self.list_address_group_references: gapic_v1.method.wrap_method( + self.list_address_group_references, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_address_groups(self) -> Callable[ + [address_group.ListAddressGroupsRequest], + Union[ + address_group.ListAddressGroupsResponse, + Awaitable[address_group.ListAddressGroupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_address_group(self) -> Callable[ + [address_group.GetAddressGroupRequest], + Union[ + address_group.AddressGroup, + Awaitable[address_group.AddressGroup] + ]]: + raise NotImplementedError() + + @property + def create_address_group(self) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_address_group(self) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_address_group_items(self) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_address_group_items(self) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def clone_address_group_items(self) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_address_group(self) -> Callable[ + [address_group.DeleteAddressGroupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_address_group_references(self) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + Union[ + gcn_address_group.ListAddressGroupReferencesResponse, + Awaitable[gcn_address_group.ListAddressGroupReferencesResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AddressGroupServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py new file mode 100644 index 000000000000..2ed4732e7b02 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py @@ -0,0 +1,768 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import AddressGroupServiceTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AddressGroupServiceGrpcTransport(AddressGroupServiceTransport): + """gRPC backend transport for AddressGroupService. + + AddressGroup is a resource that manages a collection of IP or + Domain Names, it can be used in Firewall Policy to represent + allow or deny traffic from all the IP or Domain Names from the + Address Group. + + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_address_groups(self) -> Callable[ + [address_group.ListAddressGroupsRequest], + address_group.ListAddressGroupsResponse]: + r"""Return a callable for the list address groups method over gRPC. + + Lists address groups in a given project and location. + + Returns: + Callable[[~.ListAddressGroupsRequest], + ~.ListAddressGroupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_groups' not in self._stubs: + self._stubs['list_address_groups'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroups', + request_serializer=address_group.ListAddressGroupsRequest.serialize, + response_deserializer=address_group.ListAddressGroupsResponse.deserialize, + ) + return self._stubs['list_address_groups'] + + @property + def get_address_group(self) -> Callable[ + [address_group.GetAddressGroupRequest], + address_group.AddressGroup]: + r"""Return a callable for the get address group method over gRPC. + + Gets details of a single address group. + + Returns: + Callable[[~.GetAddressGroupRequest], + ~.AddressGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_group' not in self._stubs: + self._stubs['get_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/GetAddressGroup', + request_serializer=address_group.GetAddressGroupRequest.serialize, + response_deserializer=address_group.AddressGroup.deserialize, + ) + return self._stubs['get_address_group'] + + @property + def create_address_group(self) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + operations_pb2.Operation]: + r"""Return a callable for the create address group method over gRPC. + + Creates a new address group in a given project and + location. + + Returns: + Callable[[~.CreateAddressGroupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_address_group' not in self._stubs: + self._stubs['create_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/CreateAddressGroup', + request_serializer=gcn_address_group.CreateAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_address_group'] + + @property + def update_address_group(self) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + operations_pb2.Operation]: + r"""Return a callable for the update address group method over gRPC. + + Updates the parameters of a single address group. + + Returns: + Callable[[~.UpdateAddressGroupRequest], + ~.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 'update_address_group' not in self._stubs: + self._stubs['update_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/UpdateAddressGroup', + request_serializer=gcn_address_group.UpdateAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_address_group'] + + @property + def add_address_group_items(self) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + operations_pb2.Operation]: + r"""Return a callable for the add address group items method over gRPC. + + Adds items to an address group. + + Returns: + Callable[[~.AddAddressGroupItemsRequest], + ~.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 'add_address_group_items' not in self._stubs: + self._stubs['add_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/AddAddressGroupItems', + request_serializer=gcn_address_group.AddAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_address_group_items'] + + @property + def remove_address_group_items(self) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove address group items method over gRPC. + + Removes items from an address group. + + Returns: + Callable[[~.RemoveAddressGroupItemsRequest], + ~.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 'remove_address_group_items' not in self._stubs: + self._stubs['remove_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/RemoveAddressGroupItems', + request_serializer=gcn_address_group.RemoveAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_address_group_items'] + + @property + def clone_address_group_items(self) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + operations_pb2.Operation]: + r"""Return a callable for the clone address group items method over gRPC. + + Clones items from one address group to another. + + Returns: + Callable[[~.CloneAddressGroupItemsRequest], + ~.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 'clone_address_group_items' not in self._stubs: + self._stubs['clone_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/CloneAddressGroupItems', + request_serializer=gcn_address_group.CloneAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['clone_address_group_items'] + + @property + def delete_address_group(self) -> Callable[ + [address_group.DeleteAddressGroupRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete address group method over gRPC. + + Deletes a single address group. + + Returns: + Callable[[~.DeleteAddressGroupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_address_group' not in self._stubs: + self._stubs['delete_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/DeleteAddressGroup', + request_serializer=address_group.DeleteAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_address_group'] + + @property + def list_address_group_references(self) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + gcn_address_group.ListAddressGroupReferencesResponse]: + r"""Return a callable for the list address group references method over gRPC. + + Lists references of an address group. + + Returns: + Callable[[~.ListAddressGroupReferencesRequest], + ~.ListAddressGroupReferencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_group_references' not in self._stubs: + self._stubs['list_address_group_references'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroupReferences', + request_serializer=gcn_address_group.ListAddressGroupReferencesRequest.serialize, + response_deserializer=gcn_address_group.ListAddressGroupReferencesResponse.deserialize, + ) + return self._stubs['list_address_group_references'] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AddressGroupServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..623b087a6cd4 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py @@ -0,0 +1,874 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import AddressGroupServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AddressGroupServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AddressGroupServiceGrpcAsyncIOTransport(AddressGroupServiceTransport): + """gRPC AsyncIO backend transport for AddressGroupService. + + AddressGroup is a resource that manages a collection of IP or + Domain Names, it can be used in Firewall Policy to represent + allow or deny traffic from all the IP or Domain Names from the + Address Group. + + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_address_groups(self) -> Callable[ + [address_group.ListAddressGroupsRequest], + Awaitable[address_group.ListAddressGroupsResponse]]: + r"""Return a callable for the list address groups method over gRPC. + + Lists address groups in a given project and location. + + Returns: + Callable[[~.ListAddressGroupsRequest], + Awaitable[~.ListAddressGroupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_groups' not in self._stubs: + self._stubs['list_address_groups'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroups', + request_serializer=address_group.ListAddressGroupsRequest.serialize, + response_deserializer=address_group.ListAddressGroupsResponse.deserialize, + ) + return self._stubs['list_address_groups'] + + @property + def get_address_group(self) -> Callable[ + [address_group.GetAddressGroupRequest], + Awaitable[address_group.AddressGroup]]: + r"""Return a callable for the get address group method over gRPC. + + Gets details of a single address group. + + Returns: + Callable[[~.GetAddressGroupRequest], + Awaitable[~.AddressGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_group' not in self._stubs: + self._stubs['get_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/GetAddressGroup', + request_serializer=address_group.GetAddressGroupRequest.serialize, + response_deserializer=address_group.AddressGroup.deserialize, + ) + return self._stubs['get_address_group'] + + @property + def create_address_group(self) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create address group method over gRPC. + + Creates a new address group in a given project and + location. + + Returns: + Callable[[~.CreateAddressGroupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_address_group' not in self._stubs: + self._stubs['create_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/CreateAddressGroup', + request_serializer=gcn_address_group.CreateAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_address_group'] + + @property + def update_address_group(self) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update address group method over gRPC. + + Updates the parameters of a single address group. + + Returns: + Callable[[~.UpdateAddressGroupRequest], + 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 'update_address_group' not in self._stubs: + self._stubs['update_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/UpdateAddressGroup', + request_serializer=gcn_address_group.UpdateAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_address_group'] + + @property + def add_address_group_items(self) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add address group items method over gRPC. + + Adds items to an address group. + + Returns: + Callable[[~.AddAddressGroupItemsRequest], + 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 'add_address_group_items' not in self._stubs: + self._stubs['add_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/AddAddressGroupItems', + request_serializer=gcn_address_group.AddAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_address_group_items'] + + @property + def remove_address_group_items(self) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove address group items method over gRPC. + + Removes items from an address group. + + Returns: + Callable[[~.RemoveAddressGroupItemsRequest], + 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 'remove_address_group_items' not in self._stubs: + self._stubs['remove_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/RemoveAddressGroupItems', + request_serializer=gcn_address_group.RemoveAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_address_group_items'] + + @property + def clone_address_group_items(self) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the clone address group items method over gRPC. + + Clones items from one address group to another. + + Returns: + Callable[[~.CloneAddressGroupItemsRequest], + 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 'clone_address_group_items' not in self._stubs: + self._stubs['clone_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/CloneAddressGroupItems', + request_serializer=gcn_address_group.CloneAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['clone_address_group_items'] + + @property + def delete_address_group(self) -> Callable[ + [address_group.DeleteAddressGroupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete address group method over gRPC. + + Deletes a single address group. + + Returns: + Callable[[~.DeleteAddressGroupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_address_group' not in self._stubs: + self._stubs['delete_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/DeleteAddressGroup', + request_serializer=address_group.DeleteAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_address_group'] + + @property + def list_address_group_references(self) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + Awaitable[gcn_address_group.ListAddressGroupReferencesResponse]]: + r"""Return a callable for the list address group references method over gRPC. + + Lists references of an address group. + + Returns: + Callable[[~.ListAddressGroupReferencesRequest], + Awaitable[~.ListAddressGroupReferencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_group_references' not in self._stubs: + self._stubs['list_address_group_references'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroupReferences', + request_serializer=gcn_address_group.ListAddressGroupReferencesRequest.serialize, + response_deserializer=gcn_address_group.ListAddressGroupReferencesResponse.deserialize, + ) + return self._stubs['list_address_group_references'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_address_groups: self._wrap_method( + self.list_address_groups, + default_timeout=None, + client_info=client_info, + ), + self.get_address_group: self._wrap_method( + self.get_address_group, + default_timeout=None, + client_info=client_info, + ), + self.create_address_group: self._wrap_method( + self.create_address_group, + default_timeout=None, + client_info=client_info, + ), + self.update_address_group: self._wrap_method( + self.update_address_group, + default_timeout=None, + client_info=client_info, + ), + self.add_address_group_items: self._wrap_method( + self.add_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.remove_address_group_items: self._wrap_method( + self.remove_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.clone_address_group_items: self._wrap_method( + self.clone_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.delete_address_group: self._wrap_method( + self.delete_address_group, + default_timeout=None, + client_info=client_info, + ), + self.list_address_group_references: self._wrap_method( + self.list_address_group_references, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'AddressGroupServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest.py new file mode 100644 index 000000000000..1249881d1198 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest.py @@ -0,0 +1,3043 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 +import google.protobuf + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseAddressGroupServiceRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AddressGroupServiceRestInterceptor: + """Interceptor for AddressGroupService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AddressGroupServiceRestTransport. + + .. code-block:: python + class MyCustomAddressGroupServiceInterceptor(AddressGroupServiceRestInterceptor): + def pre_add_address_group_items(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_address_group_items(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_clone_address_group_items(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_clone_address_group_items(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_address_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_address_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_address_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_address_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_address_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_address_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_address_group_references(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_address_group_references(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_address_groups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_address_groups(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_address_group_items(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_address_group_items(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_address_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_address_group(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AddressGroupServiceRestTransport(interceptor=MyCustomAddressGroupServiceInterceptor()) + client = AddressGroupServiceClient(transport=transport) + + + """ + def pre_add_address_group_items(self, request: gcn_address_group.AddAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.AddAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for add_address_group_items + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_add_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for add_address_group_items + + DEPRECATED. Please use the `post_add_address_group_items_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. This `post_add_address_group_items` interceptor runs + before the `post_add_address_group_items_with_metadata` interceptor. + """ + return response + + def post_add_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for add_address_group_items + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AddressGroupService server but before it is returned to user code. + + We recommend only using this `post_add_address_group_items_with_metadata` + interceptor in new development instead of the `post_add_address_group_items` interceptor. + When both interceptors are used, this `post_add_address_group_items_with_metadata` interceptor runs after the + `post_add_address_group_items` interceptor. The (possibly modified) response returned by + `post_add_address_group_items` will be passed to + `post_add_address_group_items_with_metadata`. + """ + return response, metadata + + def pre_clone_address_group_items(self, request: gcn_address_group.CloneAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.CloneAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for clone_address_group_items + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_clone_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for clone_address_group_items + + DEPRECATED. Please use the `post_clone_address_group_items_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. This `post_clone_address_group_items` interceptor runs + before the `post_clone_address_group_items_with_metadata` interceptor. + """ + return response + + def post_clone_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for clone_address_group_items + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AddressGroupService server but before it is returned to user code. + + We recommend only using this `post_clone_address_group_items_with_metadata` + interceptor in new development instead of the `post_clone_address_group_items` interceptor. + When both interceptors are used, this `post_clone_address_group_items_with_metadata` interceptor runs after the + `post_clone_address_group_items` interceptor. The (possibly modified) response returned by + `post_clone_address_group_items` will be passed to + `post_clone_address_group_items_with_metadata`. + """ + return response, metadata + + def pre_create_address_group(self, request: gcn_address_group.CreateAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.CreateAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_address_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_create_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_address_group + + DEPRECATED. Please use the `post_create_address_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. This `post_create_address_group` interceptor runs + before the `post_create_address_group_with_metadata` interceptor. + """ + return response + + def post_create_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_address_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AddressGroupService server but before it is returned to user code. + + We recommend only using this `post_create_address_group_with_metadata` + interceptor in new development instead of the `post_create_address_group` interceptor. + When both interceptors are used, this `post_create_address_group_with_metadata` interceptor runs after the + `post_create_address_group` interceptor. The (possibly modified) response returned by + `post_create_address_group` will be passed to + `post_create_address_group_with_metadata`. + """ + return response, metadata + + def pre_delete_address_group(self, request: address_group.DeleteAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.DeleteAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_address_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_delete_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_address_group + + DEPRECATED. Please use the `post_delete_address_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. This `post_delete_address_group` interceptor runs + before the `post_delete_address_group_with_metadata` interceptor. + """ + return response + + def post_delete_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_address_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AddressGroupService server but before it is returned to user code. + + We recommend only using this `post_delete_address_group_with_metadata` + interceptor in new development instead of the `post_delete_address_group` interceptor. + When both interceptors are used, this `post_delete_address_group_with_metadata` interceptor runs after the + `post_delete_address_group` interceptor. The (possibly modified) response returned by + `post_delete_address_group` will be passed to + `post_delete_address_group_with_metadata`. + """ + return response, metadata + + def pre_get_address_group(self, request: address_group.GetAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.GetAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_address_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_get_address_group(self, response: address_group.AddressGroup) -> address_group.AddressGroup: + """Post-rpc interceptor for get_address_group + + DEPRECATED. Please use the `post_get_address_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. This `post_get_address_group` interceptor runs + before the `post_get_address_group_with_metadata` interceptor. + """ + return response + + def post_get_address_group_with_metadata(self, response: address_group.AddressGroup, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.AddressGroup, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_address_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AddressGroupService server but before it is returned to user code. + + We recommend only using this `post_get_address_group_with_metadata` + interceptor in new development instead of the `post_get_address_group` interceptor. + When both interceptors are used, this `post_get_address_group_with_metadata` interceptor runs after the + `post_get_address_group` interceptor. The (possibly modified) response returned by + `post_get_address_group` will be passed to + `post_get_address_group_with_metadata`. + """ + return response, metadata + + def pre_list_address_group_references(self, request: gcn_address_group.ListAddressGroupReferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.ListAddressGroupReferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_address_group_references + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_list_address_group_references(self, response: gcn_address_group.ListAddressGroupReferencesResponse) -> gcn_address_group.ListAddressGroupReferencesResponse: + """Post-rpc interceptor for list_address_group_references + + DEPRECATED. Please use the `post_list_address_group_references_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. This `post_list_address_group_references` interceptor runs + before the `post_list_address_group_references_with_metadata` interceptor. + """ + return response + + def post_list_address_group_references_with_metadata(self, response: gcn_address_group.ListAddressGroupReferencesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.ListAddressGroupReferencesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_address_group_references + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AddressGroupService server but before it is returned to user code. + + We recommend only using this `post_list_address_group_references_with_metadata` + interceptor in new development instead of the `post_list_address_group_references` interceptor. + When both interceptors are used, this `post_list_address_group_references_with_metadata` interceptor runs after the + `post_list_address_group_references` interceptor. The (possibly modified) response returned by + `post_list_address_group_references` will be passed to + `post_list_address_group_references_with_metadata`. + """ + return response, metadata + + def pre_list_address_groups(self, request: address_group.ListAddressGroupsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.ListAddressGroupsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_address_groups + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_list_address_groups(self, response: address_group.ListAddressGroupsResponse) -> address_group.ListAddressGroupsResponse: + """Post-rpc interceptor for list_address_groups + + DEPRECATED. Please use the `post_list_address_groups_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. This `post_list_address_groups` interceptor runs + before the `post_list_address_groups_with_metadata` interceptor. + """ + return response + + def post_list_address_groups_with_metadata(self, response: address_group.ListAddressGroupsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.ListAddressGroupsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_address_groups + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AddressGroupService server but before it is returned to user code. + + We recommend only using this `post_list_address_groups_with_metadata` + interceptor in new development instead of the `post_list_address_groups` interceptor. + When both interceptors are used, this `post_list_address_groups_with_metadata` interceptor runs after the + `post_list_address_groups` interceptor. The (possibly modified) response returned by + `post_list_address_groups` will be passed to + `post_list_address_groups_with_metadata`. + """ + return response, metadata + + def pre_remove_address_group_items(self, request: gcn_address_group.RemoveAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.RemoveAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for remove_address_group_items + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_remove_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for remove_address_group_items + + DEPRECATED. Please use the `post_remove_address_group_items_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. This `post_remove_address_group_items` interceptor runs + before the `post_remove_address_group_items_with_metadata` interceptor. + """ + return response + + def post_remove_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for remove_address_group_items + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AddressGroupService server but before it is returned to user code. + + We recommend only using this `post_remove_address_group_items_with_metadata` + interceptor in new development instead of the `post_remove_address_group_items` interceptor. + When both interceptors are used, this `post_remove_address_group_items_with_metadata` interceptor runs after the + `post_remove_address_group_items` interceptor. The (possibly modified) response returned by + `post_remove_address_group_items` will be passed to + `post_remove_address_group_items_with_metadata`. + """ + return response, metadata + + def pre_update_address_group(self, request: gcn_address_group.UpdateAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.UpdateAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_address_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_update_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_address_group + + DEPRECATED. Please use the `post_update_address_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. This `post_update_address_group` interceptor runs + before the `post_update_address_group_with_metadata` interceptor. + """ + return response + + def post_update_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_address_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AddressGroupService server but before it is returned to user code. + + We recommend only using this `post_update_address_group_with_metadata` + interceptor in new development instead of the `post_update_address_group` interceptor. + When both interceptors are used, this `post_update_address_group_with_metadata` interceptor runs after the + `post_update_address_group` interceptor. The (possibly modified) response returned by + `post_update_address_group` will be passed to + `post_update_address_group_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AddressGroupService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the AddressGroupService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AddressGroupServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AddressGroupServiceRestInterceptor + + +class AddressGroupServiceRestTransport(_BaseAddressGroupServiceRestTransport): + """REST backend synchronous transport for AddressGroupService. + + AddressGroup is a resource that manages a collection of IP or + Domain Names, it can be used in Firewall Policy to represent + allow or deny traffic from all the IP or Domain Names from the + Address Group. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[AddressGroupServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AddressGroupServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _AddAddressGroupItems(_BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.AddAddressGroupItems") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_address_group.AddAddressGroupItemsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the add address group items method over HTTP. + + Args: + request (~.gcn_address_group.AddAddressGroupItemsRequest): + The request object. Request used by the + AddAddressGroupItems method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_http_options() + + request, metadata = self._interceptor.pre_add_address_group_items(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_transcoded_request(http_options, request) + + body = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.AddAddressGroupItems", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "AddAddressGroupItems", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._AddAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_add_address_group_items(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_add_address_group_items_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.add_address_group_items", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "AddAddressGroupItems", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CloneAddressGroupItems(_BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.CloneAddressGroupItems") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_address_group.CloneAddressGroupItemsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the clone address group items method over HTTP. + + Args: + request (~.gcn_address_group.CloneAddressGroupItemsRequest): + The request object. Request used by the + CloneAddressGroupItems method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_http_options() + + request, metadata = self._interceptor.pre_clone_address_group_items(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_transcoded_request(http_options, request) + + body = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.CloneAddressGroupItems", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "CloneAddressGroupItems", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._CloneAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_clone_address_group_items(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_clone_address_group_items_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.clone_address_group_items", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "CloneAddressGroupItems", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAddressGroup(_BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.CreateAddressGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_address_group.CreateAddressGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create address group method over HTTP. + + Args: + request (~.gcn_address_group.CreateAddressGroupRequest): + The request object. Request used by the + CreateAddressGroup method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_http_options() + + request, metadata = self._interceptor.pre_create_address_group(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_transcoded_request(http_options, request) + + body = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.CreateAddressGroup", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "CreateAddressGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._CreateAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_address_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_address_group_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.create_address_group", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "CreateAddressGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAddressGroup(_BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.DeleteAddressGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: address_group.DeleteAddressGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete address group method over HTTP. + + Args: + request (~.address_group.DeleteAddressGroupRequest): + The request object. Request used by the + DeleteAddressGroup method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_http_options() + + request, metadata = self._interceptor.pre_delete_address_group(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.DeleteAddressGroup", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "DeleteAddressGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._DeleteAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_address_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_address_group_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.delete_address_group", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "DeleteAddressGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAddressGroup(_BaseAddressGroupServiceRestTransport._BaseGetAddressGroup, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.GetAddressGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: address_group.GetAddressGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> address_group.AddressGroup: + r"""Call the get address group method over HTTP. + + Args: + request (~.address_group.GetAddressGroupRequest): + The request object. Request used by the GetAddressGroup + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.address_group.AddressGroup: + AddressGroup is a resource that + specifies how a collection of IP/DNS + used in Firewall Policy. + + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_http_options() + + request, metadata = self._interceptor.pre_get_address_group(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.GetAddressGroup", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "GetAddressGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._GetAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = address_group.AddressGroup() + pb_resp = address_group.AddressGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_address_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_address_group_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = address_group.AddressGroup.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.get_address_group", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "GetAddressGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAddressGroupReferences(_BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.ListAddressGroupReferences") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: gcn_address_group.ListAddressGroupReferencesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gcn_address_group.ListAddressGroupReferencesResponse: + r"""Call the list address group + references method over HTTP. + + Args: + request (~.gcn_address_group.ListAddressGroupReferencesRequest): + The request object. Request used by the + ListAddressGroupReferences method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcn_address_group.ListAddressGroupReferencesResponse: + Response of the + ListAddressGroupReferences method. + + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_http_options() + + request, metadata = self._interceptor.pre_list_address_group_references(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.ListAddressGroupReferences", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "ListAddressGroupReferences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._ListAddressGroupReferences._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcn_address_group.ListAddressGroupReferencesResponse() + pb_resp = gcn_address_group.ListAddressGroupReferencesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_address_group_references(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_address_group_references_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gcn_address_group.ListAddressGroupReferencesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.list_address_group_references", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "ListAddressGroupReferences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAddressGroups(_BaseAddressGroupServiceRestTransport._BaseListAddressGroups, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.ListAddressGroups") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: address_group.ListAddressGroupsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> address_group.ListAddressGroupsResponse: + r"""Call the list address groups method over HTTP. + + Args: + request (~.address_group.ListAddressGroupsRequest): + The request object. Request used with the + ListAddressGroups method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.address_group.ListAddressGroupsResponse: + Response returned by the + ListAddressGroups method. + + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_http_options() + + request, metadata = self._interceptor.pre_list_address_groups(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.ListAddressGroups", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "ListAddressGroups", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._ListAddressGroups._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = address_group.ListAddressGroupsResponse() + pb_resp = address_group.ListAddressGroupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_address_groups(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_address_groups_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = address_group.ListAddressGroupsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.list_address_groups", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "ListAddressGroups", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RemoveAddressGroupItems(_BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.RemoveAddressGroupItems") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_address_group.RemoveAddressGroupItemsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the remove address group + items method over HTTP. + + Args: + request (~.gcn_address_group.RemoveAddressGroupItemsRequest): + The request object. Request used by the + RemoveAddressGroupItems method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_http_options() + + request, metadata = self._interceptor.pre_remove_address_group_items(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_transcoded_request(http_options, request) + + body = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.RemoveAddressGroupItems", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "RemoveAddressGroupItems", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._RemoveAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_remove_address_group_items(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_remove_address_group_items_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.remove_address_group_items", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "RemoveAddressGroupItems", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAddressGroup(_BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.UpdateAddressGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_address_group.UpdateAddressGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update address group method over HTTP. + + Args: + request (~.gcn_address_group.UpdateAddressGroupRequest): + The request object. Request used by the + UpdateAddressGroup method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_http_options() + + request, metadata = self._interceptor.pre_update_address_group(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_transcoded_request(http_options, request) + + body = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.UpdateAddressGroup", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "UpdateAddressGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._UpdateAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_address_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_address_group_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.update_address_group", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "UpdateAddressGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def add_address_group_items(self) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AddAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + + @property + def clone_address_group_items(self) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CloneAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_address_group(self) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAddressGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_address_group(self) -> Callable[ + [address_group.DeleteAddressGroupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAddressGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_address_group(self) -> Callable[ + [address_group.GetAddressGroupRequest], + address_group.AddressGroup]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAddressGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_address_group_references(self) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + gcn_address_group.ListAddressGroupReferencesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAddressGroupReferences(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_address_groups(self) -> Callable[ + [address_group.ListAddressGroupsRequest], + address_group.ListAddressGroupsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAddressGroups(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_address_group_items(self) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RemoveAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_address_group(self) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAddressGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseAddressGroupServiceRestTransport._BaseGetLocation, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseGetLocation._get_http_options() + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.GetLocation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.GetLocation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseAddressGroupServiceRestTransport._BaseListLocations, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseListLocations._get_http_options() + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.ListLocations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.ListLocations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseAddressGroupServiceRestTransport._BaseGetIamPolicy, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseGetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.GetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.GetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseAddressGroupServiceRestTransport._BaseSetIamPolicy, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.SetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.SetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseAddressGroupServiceRestTransport._BaseTestIamPermissions, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.TestIamPermissions", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.TestIamPermissions", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseAddressGroupServiceRestTransport._BaseCancelOperation, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.CancelOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseAddressGroupServiceRestTransport._BaseDeleteOperation, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseAddressGroupServiceRestTransport._BaseGetOperation, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.GetOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseAddressGroupServiceRestTransport._BaseListOperations, AddressGroupServiceRestStub): + def __hash__(self): + return hash("AddressGroupServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseAddressGroupServiceRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAddressGroupServiceRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.ListOperations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AddressGroupServiceRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AddressGroupServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py new file mode 100644 index 000000000000..86a018236de1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py @@ -0,0 +1,800 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import AddressGroupServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseAddressGroupServiceRestTransport(AddressGroupServiceTransport): + """Base REST backend transport for AddressGroupService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[Any]): 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. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseAddAddressGroupItems: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{address_group=projects/*/locations/*/addressGroups/*}:addItems', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.AddAddressGroupItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCloneAddressGroupItems: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{address_group=projects/*/locations/*/addressGroups/*}:cloneItems', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.CloneAddressGroupItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateAddressGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "addressGroupId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/addressGroups', + 'body': 'address_group', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.CreateAddressGroupRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteAddressGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/addressGroups/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = address_group.DeleteAddressGroupRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAddressGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/addressGroups/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = address_group.GetAddressGroupRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAddressGroupReferences: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{address_group=projects/*/locations/*/addressGroups/*}:listReferences', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.ListAddressGroupReferencesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAddressGroups: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/addressGroups', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = address_group.ListAddressGroupsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveAddressGroupItems: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{address_group=projects/*/locations/*/addressGroups/*}:removeItems', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.RemoveAddressGroupItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAddressGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{address_group.name=projects/*/locations/*/addressGroups/*}', + 'body': 'address_group', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.UpdateAddressGroupRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}/operations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseAddressGroupServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/__init__.py new file mode 100644 index 000000000000..cddb3cfba9e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 NetworkSecurityClient +from .async_client import NetworkSecurityAsyncClient + +__all__ = ( + 'NetworkSecurityClient', + 'NetworkSecurityAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/async_client.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/async_client.py new file mode 100644 index 000000000000..ee7c91c0d573 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/async_client.py @@ -0,0 +1,2866 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.network_security_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.services.network_security import pagers +from google.cloud.network_security_v1.types import authorization_policy +from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1.types import client_tls_policy +from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1.types import common +from google.cloud.network_security_v1.types import server_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy +from google.cloud.network_security_v1.types import tls +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport +from .client import NetworkSecurityClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class NetworkSecurityAsyncClient: + """Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + """ + + _client: NetworkSecurityClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = NetworkSecurityClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = NetworkSecurityClient._DEFAULT_UNIVERSE + + authorization_policy_path = staticmethod(NetworkSecurityClient.authorization_policy_path) + parse_authorization_policy_path = staticmethod(NetworkSecurityClient.parse_authorization_policy_path) + client_tls_policy_path = staticmethod(NetworkSecurityClient.client_tls_policy_path) + parse_client_tls_policy_path = staticmethod(NetworkSecurityClient.parse_client_tls_policy_path) + server_tls_policy_path = staticmethod(NetworkSecurityClient.server_tls_policy_path) + parse_server_tls_policy_path = staticmethod(NetworkSecurityClient.parse_server_tls_policy_path) + common_billing_account_path = staticmethod(NetworkSecurityClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(NetworkSecurityClient.parse_common_billing_account_path) + common_folder_path = staticmethod(NetworkSecurityClient.common_folder_path) + parse_common_folder_path = staticmethod(NetworkSecurityClient.parse_common_folder_path) + common_organization_path = staticmethod(NetworkSecurityClient.common_organization_path) + parse_common_organization_path = staticmethod(NetworkSecurityClient.parse_common_organization_path) + common_project_path = staticmethod(NetworkSecurityClient.common_project_path) + parse_common_project_path = staticmethod(NetworkSecurityClient.parse_common_project_path) + common_location_path = staticmethod(NetworkSecurityClient.common_location_path) + parse_common_location_path = staticmethod(NetworkSecurityClient.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: + NetworkSecurityAsyncClient: The constructed client. + """ + return NetworkSecurityClient.from_service_account_info.__func__(NetworkSecurityAsyncClient, 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: + NetworkSecurityAsyncClient: The constructed client. + """ + return NetworkSecurityClient.from_service_account_file.__func__(NetworkSecurityAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return NetworkSecurityClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> NetworkSecurityTransport: + """Returns the transport used by the client instance. + + Returns: + NetworkSecurityTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = NetworkSecurityClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the network security async 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the NetworkSecurityTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = NetworkSecurityClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networksecurity_v1.NetworkSecurityAsyncClient`.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "credentialsType": None, + } + ) + + async def list_authorization_policies(self, + request: Optional[Union[authorization_policy.ListAuthorizationPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAuthorizationPoliciesAsyncPager: + r"""Lists AuthorizationPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_authorization_policies(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListAuthorizationPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_authorization_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest, dict]]): + The request object. Request used with the + ListAuthorizationPolicies method. + parent (:class:`str`): + Required. The project and location from which the + AuthorizationPolicies should be listed, specified in the + format ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager: + Response returned by the + ListAuthorizationPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.ListAuthorizationPoliciesRequest): + request = authorization_policy.ListAuthorizationPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_authorization_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAuthorizationPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_authorization_policy(self, + request: Optional[Union[authorization_policy.GetAuthorizationPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> authorization_policy.AuthorizationPolicy: + r"""Gets details of a single AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_get_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_authorization_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest, dict]]): + The request object. Request used by the + GetAuthorizationPolicy method. + name (:class:`str`): + Required. A name of the AuthorizationPolicy to get. Must + be in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.types.AuthorizationPolicy: + AuthorizationPolicy is a resource + that specifies how a server should + authorize incoming connections. This + resource in itself does not change the + configuration unless it's attached to a + target https proxy or endpoint config + selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.GetAuthorizationPolicyRequest): + request = authorization_policy.GetAuthorizationPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_authorization_policy(self, + request: Optional[Union[gcn_authorization_policy.CreateAuthorizationPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, + authorization_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new AuthorizationPolicy in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_create_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1.CreateAuthorizationPolicyRequest( + parent="parent_value", + authorization_policy_id="authorization_policy_id_value", + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.create_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest, dict]]): + The request object. Request used by the + CreateAuthorizationPolicy method. + parent (:class:`str`): + Required. The parent resource of the + AuthorizationPolicy. Must be in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + authorization_policy (:class:`google.cloud.network_security_v1.types.AuthorizationPolicy`): + Required. AuthorizationPolicy + resource to be created. + + This corresponds to the ``authorization_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + authorization_policy_id (:class:`str`): + Required. Short name of the AuthorizationPolicy resource + to be created. This value should be 1-63 characters + long, containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "authz_policy". + + This corresponds to the ``authorization_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server + should authorize incoming connections. This resource + in itself does not change the configuration unless + it's attached to a target https proxy or endpoint + config selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, authorization_policy, authorization_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_authorization_policy.CreateAuthorizationPolicyRequest): + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if authorization_policy is not None: + request.authorization_policy = authorization_policy + if authorization_policy_id is not None: + request.authorization_policy_id = authorization_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_authorization_policy.AuthorizationPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_authorization_policy(self, + request: Optional[Union[gcn_authorization_policy.UpdateAuthorizationPolicyRequest, dict]] = None, + *, + authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single + AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_update_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1.UpdateAuthorizationPolicyRequest( + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.update_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest, dict]]): + The request object. Request used by the + UpdateAuthorizationPolicy method. + authorization_policy (:class:`google.cloud.network_security_v1.types.AuthorizationPolicy`): + Required. Updated AuthorizationPolicy + resource. + + This corresponds to the ``authorization_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the AuthorizationPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server + should authorize incoming connections. This resource + in itself does not change the configuration unless + it's attached to a target https proxy or endpoint + config selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [authorization_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_authorization_policy.UpdateAuthorizationPolicyRequest): + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if authorization_policy is not None: + request.authorization_policy = authorization_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_authorization_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("authorization_policy.name", request.authorization_policy.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_authorization_policy.AuthorizationPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_authorization_policy(self, + request: Optional[Union[authorization_policy.DeleteAuthorizationPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_delete_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest, dict]]): + The request object. Request used by the + DeleteAuthorizationPolicy method. + name (:class:`str`): + Required. A name of the AuthorizationPolicy to delete. + Must be in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.DeleteAuthorizationPolicyRequest): + request = authorization_policy.DeleteAuthorizationPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_server_tls_policies(self, + request: Optional[Union[server_tls_policy.ListServerTlsPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListServerTlsPoliciesAsyncPager: + r"""Lists ServerTlsPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_server_tls_policies(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListServerTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_server_tls_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest, dict]]): + The request object. Request used by the + ListServerTlsPolicies method. + parent (:class:`str`): + Required. The project and location from which the + ServerTlsPolicies should be listed, specified in the + format ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager: + Response returned by the + ListServerTlsPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.ListServerTlsPoliciesRequest): + request = server_tls_policy.ListServerTlsPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_server_tls_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListServerTlsPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_server_tls_policy(self, + request: Optional[Union[server_tls_policy.GetServerTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> server_tls_policy.ServerTlsPolicy: + r"""Gets details of a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_get_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_server_tls_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetServerTlsPolicyRequest, dict]]): + The request object. Request used by the + GetServerTlsPolicy method. + name (:class:`str`): + Required. A name of the ServerTlsPolicy to get. Must be + in the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.types.ServerTlsPolicy: + ServerTlsPolicy is a resource that + specifies how a server should + authenticate incoming requests. This + resource itself does not affect + configuration unless it is attached to a + target https proxy or endpoint config + selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.GetServerTlsPolicyRequest): + request = server_tls_policy.GetServerTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_server_tls_policy(self, + request: Optional[Union[gcn_server_tls_policy.CreateServerTlsPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, + server_tls_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ServerTlsPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_create_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1.CreateServerTlsPolicyRequest( + parent="parent_value", + server_tls_policy_id="server_tls_policy_id_value", + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.create_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest, dict]]): + The request object. Request used by the + CreateServerTlsPolicy method. + parent (:class:`str`): + Required. The parent resource of the ServerTlsPolicy. + Must be in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + server_tls_policy (:class:`google.cloud.network_security_v1.types.ServerTlsPolicy`): + Required. ServerTlsPolicy resource to + be created. + + This corresponds to the ``server_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + server_tls_policy_id (:class:`str`): + Required. Short name of the ServerTlsPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "server_mtls_policy". + + This corresponds to the ``server_tls_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate + incoming requests. This resource itself does not + affect configuration unless it is attached to a + target https proxy or endpoint config selector + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, server_tls_policy, server_tls_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_server_tls_policy.CreateServerTlsPolicyRequest): + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if server_tls_policy is not None: + request.server_tls_policy = server_tls_policy + if server_tls_policy_id is not None: + request.server_tls_policy_id = server_tls_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_server_tls_policy.ServerTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_server_tls_policy(self, + request: Optional[Union[gcn_server_tls_policy.UpdateServerTlsPolicyRequest, dict]] = None, + *, + server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_update_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1.UpdateServerTlsPolicyRequest( + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.update_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest, dict]]): + The request object. Request used by UpdateServerTlsPolicy + method. + server_tls_policy (:class:`google.cloud.network_security_v1.types.ServerTlsPolicy`): + Required. Updated ServerTlsPolicy + resource. + + This corresponds to the ``server_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the ServerTlsPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate + incoming requests. This resource itself does not + affect configuration unless it is attached to a + target https proxy or endpoint config selector + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [server_tls_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_server_tls_policy.UpdateServerTlsPolicyRequest): + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if server_tls_policy is not None: + request.server_tls_policy = server_tls_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_server_tls_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("server_tls_policy.name", request.server_tls_policy.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_server_tls_policy.ServerTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_server_tls_policy(self, + request: Optional[Union[server_tls_policy.DeleteServerTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_delete_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest, dict]]): + The request object. Request used by the + DeleteServerTlsPolicy method. + name (:class:`str`): + Required. A name of the ServerTlsPolicy to delete. Must + be in the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.DeleteServerTlsPolicyRequest): + request = server_tls_policy.DeleteServerTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_client_tls_policies(self, + request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListClientTlsPoliciesAsyncPager: + r"""Lists ClientTlsPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest, dict]]): + The request object. Request used by the + ListClientTlsPolicies method. + parent (:class:`str`): + Required. The project and location from which the + ClientTlsPolicies should be listed, specified in the + format ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager: + Response returned by the + ListClientTlsPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): + request = client_tls_policy.ListClientTlsPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_client_tls_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListClientTlsPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_client_tls_policy(self, + request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> client_tls_policy.ClientTlsPolicy: + r"""Gets details of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetClientTlsPolicyRequest, dict]]): + The request object. Request used by the + GetClientTlsPolicy method. + name (:class:`str`): + Required. A name of the ClientTlsPolicy to get. Must be + in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.types.ClientTlsPolicy: + ClientTlsPolicy is a resource that + specifies how a client should + authenticate connections to backends of + a service. This resource itself does not + affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): + request = client_tls_policy.GetClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + client_tls_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ClientTlsPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest, dict]]): + The request object. Request used by the + CreateClientTlsPolicy method. + parent (:class:`str`): + Required. The parent resource of the ClientTlsPolicy. + Must be in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy (:class:`google.cloud.network_security_v1.types.ClientTlsPolicy`): + Required. ClientTlsPolicy resource to + be created. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy_id (:class:`str`): + Required. Short name of the ClientTlsPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "client_mtls_policy". + + This corresponds to the ``client_tls_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, client_tls_policy, client_tls_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if client_tls_policy_id is not None: + request.client_tls_policy_id = client_tls_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, + *, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest, dict]]): + The request object. Request used by UpdateClientTlsPolicy + method. + client_tls_policy (:class:`google.cloud.network_security_v1.types.ClientTlsPolicy`): + Required. Updated ClientTlsPolicy + resource. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the ClientTlsPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [client_tls_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_client_tls_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("client_tls_policy.name", request.client_tls_policy.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_client_tls_policy(self, + request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest, dict]]): + The request object. Request used by the + DeleteClientTlsPolicy method. + name (:class:`str`): + Required. A name of the ClientTlsPolicy to delete. Must + be in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): + request = client_tls_policy.DeleteClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "NetworkSecurityAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "NetworkSecurityAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/client.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/client.py new file mode 100644 index 000000000000..c07f553c447b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/client.py @@ -0,0 +1,3253 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.network_security_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.services.network_security import pagers +from google.cloud.network_security_v1.types import authorization_policy +from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1.types import client_tls_policy +from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1.types import common +from google.cloud.network_security_v1.types import server_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy +from google.cloud.network_security_v1.types import tls +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import NetworkSecurityGrpcTransport +from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport +from .transports.rest import NetworkSecurityRestTransport + + +class NetworkSecurityClientMeta(type): + """Metaclass for the NetworkSecurity 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[NetworkSecurityTransport]] + _transport_registry["grpc"] = NetworkSecurityGrpcTransport + _transport_registry["grpc_asyncio"] = NetworkSecurityGrpcAsyncIOTransport + _transport_registry["rest"] = NetworkSecurityRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[NetworkSecurityTransport]: + """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 NetworkSecurityClient(metaclass=NetworkSecurityClientMeta): + """Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "networksecurity.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networksecurity.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + NetworkSecurityClient: 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: + NetworkSecurityClient: 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) -> NetworkSecurityTransport: + """Returns the transport used by the client instance. + + Returns: + NetworkSecurityTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def authorization_policy_path(project: str,location: str,authorization_policy: str,) -> str: + """Returns a fully-qualified authorization_policy string.""" + return "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format(project=project, location=location, authorization_policy=authorization_policy, ) + + @staticmethod + def parse_authorization_policy_path(path: str) -> Dict[str,str]: + """Parses a authorization_policy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/authorizationPolicies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def client_tls_policy_path(project: str,location: str,client_tls_policy: str,) -> str: + """Returns a fully-qualified client_tls_policy string.""" + return "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) + + @staticmethod + def parse_client_tls_policy_path(path: str) -> Dict[str,str]: + """Parses a client_tls_policy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clientTlsPolicies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def server_tls_policy_path(project: str,location: str,server_tls_policy: str,) -> str: + """Returns a fully-qualified server_tls_policy string.""" + return "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format(project=project, location=location, server_tls_policy=server_tls_policy, ) + + @staticmethod + def parse_server_tls_policy_path(path: str) -> Dict[str,str]: + """Parses a server_tls_policy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/serverTlsPolicies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = NetworkSecurityClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the network security 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the NetworkSecurityTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = NetworkSecurityClient._read_environment_variables() + self._client_cert_source = NetworkSecurityClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = NetworkSecurityClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, NetworkSecurityTransport) + if transport_provided: + # transport is a NetworkSecurityTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(NetworkSecurityTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + NetworkSecurityClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[NetworkSecurityTransport], Callable[..., NetworkSecurityTransport]] = ( + NetworkSecurityClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., NetworkSecurityTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networksecurity_v1.NetworkSecurityClient`.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "credentialsType": None, + } + ) + + def list_authorization_policies(self, + request: Optional[Union[authorization_policy.ListAuthorizationPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAuthorizationPoliciesPager: + r"""Lists AuthorizationPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_authorization_policies(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.ListAuthorizationPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_authorization_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest, dict]): + The request object. Request used with the + ListAuthorizationPolicies method. + parent (str): + Required. The project and location from which the + AuthorizationPolicies should be listed, specified in the + format ``projects/{project}/locations/{location}``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesPager: + Response returned by the + ListAuthorizationPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.ListAuthorizationPoliciesRequest): + request = authorization_policy.ListAuthorizationPoliciesRequest(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_authorization_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAuthorizationPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_authorization_policy(self, + request: Optional[Union[authorization_policy.GetAuthorizationPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> authorization_policy.AuthorizationPolicy: + r"""Gets details of a single AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_get_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.GetAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_authorization_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest, dict]): + The request object. Request used by the + GetAuthorizationPolicy method. + name (str): + Required. A name of the AuthorizationPolicy to get. Must + be in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.types.AuthorizationPolicy: + AuthorizationPolicy is a resource + that specifies how a server should + authorize incoming connections. This + resource in itself does not change the + configuration unless it's attached to a + target https proxy or endpoint config + selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.GetAuthorizationPolicyRequest): + request = authorization_policy.GetAuthorizationPolicyRequest(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_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_authorization_policy(self, + request: Optional[Union[gcn_authorization_policy.CreateAuthorizationPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, + authorization_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new AuthorizationPolicy in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_create_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1.CreateAuthorizationPolicyRequest( + parent="parent_value", + authorization_policy_id="authorization_policy_id_value", + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.create_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest, dict]): + The request object. Request used by the + CreateAuthorizationPolicy method. + parent (str): + Required. The parent resource of the + AuthorizationPolicy. Must be in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + authorization_policy (google.cloud.network_security_v1.types.AuthorizationPolicy): + Required. AuthorizationPolicy + resource to be created. + + This corresponds to the ``authorization_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + authorization_policy_id (str): + Required. Short name of the AuthorizationPolicy resource + to be created. This value should be 1-63 characters + long, containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "authz_policy". + + This corresponds to the ``authorization_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server + should authorize incoming connections. This resource + in itself does not change the configuration unless + it's attached to a target https proxy or endpoint + config selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, authorization_policy, authorization_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_authorization_policy.CreateAuthorizationPolicyRequest): + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if authorization_policy is not None: + request.authorization_policy = authorization_policy + if authorization_policy_id is not None: + request.authorization_policy_id = authorization_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_authorization_policy.AuthorizationPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_authorization_policy(self, + request: Optional[Union[gcn_authorization_policy.UpdateAuthorizationPolicyRequest, dict]] = None, + *, + authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single + AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_update_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1.UpdateAuthorizationPolicyRequest( + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.update_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest, dict]): + The request object. Request used by the + UpdateAuthorizationPolicy method. + authorization_policy (google.cloud.network_security_v1.types.AuthorizationPolicy): + Required. Updated AuthorizationPolicy + resource. + + This corresponds to the ``authorization_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the AuthorizationPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server + should authorize incoming connections. This resource + in itself does not change the configuration unless + it's attached to a target https proxy or endpoint + config selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [authorization_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_authorization_policy.UpdateAuthorizationPolicyRequest): + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if authorization_policy is not None: + request.authorization_policy = authorization_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_authorization_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("authorization_policy.name", request.authorization_policy.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_authorization_policy.AuthorizationPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_authorization_policy(self, + request: Optional[Union[authorization_policy.DeleteAuthorizationPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_delete_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest, dict]): + The request object. Request used by the + DeleteAuthorizationPolicy method. + name (str): + Required. A name of the AuthorizationPolicy to delete. + Must be in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.DeleteAuthorizationPolicyRequest): + request = authorization_policy.DeleteAuthorizationPolicyRequest(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_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_server_tls_policies(self, + request: Optional[Union[server_tls_policy.ListServerTlsPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListServerTlsPoliciesPager: + r"""Lists ServerTlsPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_server_tls_policies(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.ListServerTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_server_tls_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest, dict]): + The request object. Request used by the + ListServerTlsPolicies method. + parent (str): + Required. The project and location from which the + ServerTlsPolicies should be listed, specified in the + format ``projects/*/locations/{location}``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesPager: + Response returned by the + ListServerTlsPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.ListServerTlsPoliciesRequest): + request = server_tls_policy.ListServerTlsPoliciesRequest(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_server_tls_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListServerTlsPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_server_tls_policy(self, + request: Optional[Union[server_tls_policy.GetServerTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> server_tls_policy.ServerTlsPolicy: + r"""Gets details of a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_get_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.GetServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_server_tls_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetServerTlsPolicyRequest, dict]): + The request object. Request used by the + GetServerTlsPolicy method. + name (str): + Required. A name of the ServerTlsPolicy to get. Must be + in the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.types.ServerTlsPolicy: + ServerTlsPolicy is a resource that + specifies how a server should + authenticate incoming requests. This + resource itself does not affect + configuration unless it is attached to a + target https proxy or endpoint config + selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.GetServerTlsPolicyRequest): + request = server_tls_policy.GetServerTlsPolicyRequest(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_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_server_tls_policy(self, + request: Optional[Union[gcn_server_tls_policy.CreateServerTlsPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, + server_tls_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new ServerTlsPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_create_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1.CreateServerTlsPolicyRequest( + parent="parent_value", + server_tls_policy_id="server_tls_policy_id_value", + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.create_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest, dict]): + The request object. Request used by the + CreateServerTlsPolicy method. + parent (str): + Required. The parent resource of the ServerTlsPolicy. + Must be in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + server_tls_policy (google.cloud.network_security_v1.types.ServerTlsPolicy): + Required. ServerTlsPolicy resource to + be created. + + This corresponds to the ``server_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + server_tls_policy_id (str): + Required. Short name of the ServerTlsPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "server_mtls_policy". + + This corresponds to the ``server_tls_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate + incoming requests. This resource itself does not + affect configuration unless it is attached to a + target https proxy or endpoint config selector + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, server_tls_policy, server_tls_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_server_tls_policy.CreateServerTlsPolicyRequest): + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if server_tls_policy is not None: + request.server_tls_policy = server_tls_policy + if server_tls_policy_id is not None: + request.server_tls_policy_id = server_tls_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_server_tls_policy.ServerTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_server_tls_policy(self, + request: Optional[Union[gcn_server_tls_policy.UpdateServerTlsPolicyRequest, dict]] = None, + *, + server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_update_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1.UpdateServerTlsPolicyRequest( + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.update_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest, dict]): + The request object. Request used by UpdateServerTlsPolicy + method. + server_tls_policy (google.cloud.network_security_v1.types.ServerTlsPolicy): + Required. Updated ServerTlsPolicy + resource. + + This corresponds to the ``server_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ServerTlsPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate + incoming requests. This resource itself does not + affect configuration unless it is attached to a + target https proxy or endpoint config selector + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [server_tls_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_server_tls_policy.UpdateServerTlsPolicyRequest): + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if server_tls_policy is not None: + request.server_tls_policy = server_tls_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_server_tls_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("server_tls_policy.name", request.server_tls_policy.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_server_tls_policy.ServerTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_server_tls_policy(self, + request: Optional[Union[server_tls_policy.DeleteServerTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_delete_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest, dict]): + The request object. Request used by the + DeleteServerTlsPolicy method. + name (str): + Required. A name of the ServerTlsPolicy to delete. Must + be in the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.DeleteServerTlsPolicyRequest): + request = server_tls_policy.DeleteServerTlsPolicyRequest(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_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_client_tls_policies(self, + request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListClientTlsPoliciesPager: + r"""Lists ClientTlsPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest, dict]): + The request object. Request used by the + ListClientTlsPolicies method. + parent (str): + Required. The project and location from which the + ClientTlsPolicies should be listed, specified in the + format ``projects/*/locations/{location}``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesPager: + Response returned by the + ListClientTlsPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): + request = client_tls_policy.ListClientTlsPoliciesRequest(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_client_tls_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListClientTlsPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_client_tls_policy(self, + request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> client_tls_policy.ClientTlsPolicy: + r"""Gets details of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetClientTlsPolicyRequest, dict]): + The request object. Request used by the + GetClientTlsPolicy method. + name (str): + Required. A name of the ClientTlsPolicy to get. Must be + in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.types.ClientTlsPolicy: + ClientTlsPolicy is a resource that + specifies how a client should + authenticate connections to backends of + a service. This resource itself does not + affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): + request = client_tls_policy.GetClientTlsPolicyRequest(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_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + client_tls_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new ClientTlsPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest, dict]): + The request object. Request used by the + CreateClientTlsPolicy method. + parent (str): + Required. The parent resource of the ClientTlsPolicy. + Must be in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy (google.cloud.network_security_v1.types.ClientTlsPolicy): + Required. ClientTlsPolicy resource to + be created. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy_id (str): + Required. Short name of the ClientTlsPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "client_mtls_policy". + + This corresponds to the ``client_tls_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, client_tls_policy, client_tls_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if client_tls_policy_id is not None: + request.client_tls_policy_id = client_tls_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, + *, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest, dict]): + The request object. Request used by UpdateClientTlsPolicy + method. + client_tls_policy (google.cloud.network_security_v1.types.ClientTlsPolicy): + Required. Updated ClientTlsPolicy + resource. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ClientTlsPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [client_tls_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_client_tls_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("client_tls_policy.name", request.client_tls_policy.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_client_tls_policy(self, + request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest, dict]): + The request object. Request used by the + DeleteClientTlsPolicy method. + name (str): + Required. A name of the ClientTlsPolicy to delete. Must + be in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): + request = client_tls_policy.DeleteClientTlsPolicyRequest(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_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "NetworkSecurityClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "NetworkSecurityClient", +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/pagers.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/pagers.py new file mode 100644 index 000000000000..1e2812463cc6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/pagers.py @@ -0,0 +1,446 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.network_security_v1.types import authorization_policy +from google.cloud.network_security_v1.types import client_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy + + +class ListAuthorizationPoliciesPager: + """A pager for iterating through ``list_authorization_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``authorization_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAuthorizationPolicies`` requests and continue to iterate + through the ``authorization_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse` + 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[..., authorization_policy.ListAuthorizationPoliciesResponse], + request: authorization_policy.ListAuthorizationPoliciesRequest, + response: authorization_policy.ListAuthorizationPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = authorization_policy.ListAuthorizationPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[authorization_policy.ListAuthorizationPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[authorization_policy.AuthorizationPolicy]: + for page in self.pages: + yield from page.authorization_policies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAuthorizationPoliciesAsyncPager: + """A pager for iterating through ``list_authorization_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``authorization_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAuthorizationPolicies`` requests and continue to iterate + through the ``authorization_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse` + 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[authorization_policy.ListAuthorizationPoliciesResponse]], + request: authorization_policy.ListAuthorizationPoliciesRequest, + response: authorization_policy.ListAuthorizationPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = authorization_policy.ListAuthorizationPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[authorization_policy.ListAuthorizationPoliciesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[authorization_policy.AuthorizationPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.authorization_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServerTlsPoliciesPager: + """A pager for iterating through ``list_server_tls_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``server_tls_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServerTlsPolicies`` requests and continue to iterate + through the ``server_tls_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse` + 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[..., server_tls_policy.ListServerTlsPoliciesResponse], + request: server_tls_policy.ListServerTlsPoliciesRequest, + response: server_tls_policy.ListServerTlsPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = server_tls_policy.ListServerTlsPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[server_tls_policy.ListServerTlsPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[server_tls_policy.ServerTlsPolicy]: + for page in self.pages: + yield from page.server_tls_policies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServerTlsPoliciesAsyncPager: + """A pager for iterating through ``list_server_tls_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``server_tls_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServerTlsPolicies`` requests and continue to iterate + through the ``server_tls_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse` + 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[server_tls_policy.ListServerTlsPoliciesResponse]], + request: server_tls_policy.ListServerTlsPoliciesRequest, + response: server_tls_policy.ListServerTlsPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = server_tls_policy.ListServerTlsPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[server_tls_policy.ListServerTlsPoliciesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[server_tls_policy.ServerTlsPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.server_tls_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListClientTlsPoliciesPager: + """A pager for iterating through ``list_client_tls_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``client_tls_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListClientTlsPolicies`` requests and continue to iterate + through the ``client_tls_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse` + 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[..., client_tls_policy.ListClientTlsPoliciesResponse], + request: client_tls_policy.ListClientTlsPoliciesRequest, + response: client_tls_policy.ListClientTlsPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[client_tls_policy.ListClientTlsPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[client_tls_policy.ClientTlsPolicy]: + for page in self.pages: + yield from page.client_tls_policies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListClientTlsPoliciesAsyncPager: + """A pager for iterating through ``list_client_tls_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``client_tls_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListClientTlsPolicies`` requests and continue to iterate + through the ``client_tls_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse` + 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[client_tls_policy.ListClientTlsPoliciesResponse]], + request: client_tls_policy.ListClientTlsPoliciesRequest, + response: client_tls_policy.ListClientTlsPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[client_tls_policy.ListClientTlsPoliciesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[client_tls_policy.ClientTlsPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.client_tls_policies: + 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/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/README.rst b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/README.rst new file mode 100644 index 000000000000..e226a3cdbadb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`NetworkSecurityTransport` is the ABC for all transports. +- public child `NetworkSecurityGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `NetworkSecurityGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseNetworkSecurityRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `NetworkSecurityRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/__init__.py new file mode 100644 index 000000000000..6ee9817a2d9e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 NetworkSecurityTransport +from .grpc import NetworkSecurityGrpcTransport +from .grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport +from .rest import NetworkSecurityRestTransport +from .rest import NetworkSecurityRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[NetworkSecurityTransport]] +_transport_registry['grpc'] = NetworkSecurityGrpcTransport +_transport_registry['grpc_asyncio'] = NetworkSecurityGrpcAsyncIOTransport +_transport_registry['rest'] = NetworkSecurityRestTransport + +__all__ = ( + 'NetworkSecurityTransport', + 'NetworkSecurityGrpcTransport', + 'NetworkSecurityGrpcAsyncIOTransport', + 'NetworkSecurityRestTransport', + 'NetworkSecurityRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/base.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/base.py new file mode 100644 index 000000000000..b08d873ced14 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/base.py @@ -0,0 +1,497 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.network_security_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.types import authorization_policy +from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1.types import client_tls_policy +from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class NetworkSecurityTransport(abc.ABC): + """Abstract transport class for NetworkSecurity.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'networksecurity.googleapis.com' + + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_authorization_policies: gapic_v1.method.wrap_method( + self.list_authorization_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_authorization_policy: gapic_v1.method.wrap_method( + self.get_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_authorization_policy: gapic_v1.method.wrap_method( + self.create_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_authorization_policy: gapic_v1.method.wrap_method( + self.update_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_authorization_policy: gapic_v1.method.wrap_method( + self.delete_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_server_tls_policies: gapic_v1.method.wrap_method( + self.list_server_tls_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_server_tls_policy: gapic_v1.method.wrap_method( + self.get_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_server_tls_policy: gapic_v1.method.wrap_method( + self.create_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_server_tls_policy: gapic_v1.method.wrap_method( + self.update_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_server_tls_policy: gapic_v1.method.wrap_method( + self.delete_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_client_tls_policies: gapic_v1.method.wrap_method( + self.list_client_tls_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_client_tls_policy: gapic_v1.method.wrap_method( + self.get_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_client_tls_policy: gapic_v1.method.wrap_method( + self.create_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_client_tls_policy: gapic_v1.method.wrap_method( + self.update_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_client_tls_policy: gapic_v1.method.wrap_method( + self.delete_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_authorization_policies(self) -> Callable[ + [authorization_policy.ListAuthorizationPoliciesRequest], + Union[ + authorization_policy.ListAuthorizationPoliciesResponse, + Awaitable[authorization_policy.ListAuthorizationPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def get_authorization_policy(self) -> Callable[ + [authorization_policy.GetAuthorizationPolicyRequest], + Union[ + authorization_policy.AuthorizationPolicy, + Awaitable[authorization_policy.AuthorizationPolicy] + ]]: + raise NotImplementedError() + + @property + def create_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.CreateAuthorizationPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_authorization_policy(self) -> Callable[ + [authorization_policy.DeleteAuthorizationPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_server_tls_policies(self) -> Callable[ + [server_tls_policy.ListServerTlsPoliciesRequest], + Union[ + server_tls_policy.ListServerTlsPoliciesResponse, + Awaitable[server_tls_policy.ListServerTlsPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def get_server_tls_policy(self) -> Callable[ + [server_tls_policy.GetServerTlsPolicyRequest], + Union[ + server_tls_policy.ServerTlsPolicy, + Awaitable[server_tls_policy.ServerTlsPolicy] + ]]: + raise NotImplementedError() + + @property + def create_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.CreateServerTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_server_tls_policy(self) -> Callable[ + [server_tls_policy.DeleteServerTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + Union[ + client_tls_policy.ListClientTlsPoliciesResponse, + Awaitable[client_tls_policy.ListClientTlsPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + Union[ + client_tls_policy.ClientTlsPolicy, + Awaitable[client_tls_policy.ClientTlsPolicy] + ]]: + raise NotImplementedError() + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'NetworkSecurityTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc.py new file mode 100644 index 000000000000..9a59b60498df --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc.py @@ -0,0 +1,933 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.types import authorization_policy +from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1.types import client_tls_policy +from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class NetworkSecurityGrpcTransport(NetworkSecurityTransport): + """gRPC backend transport for NetworkSecurity. + + Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_authorization_policies(self) -> Callable[ + [authorization_policy.ListAuthorizationPoliciesRequest], + authorization_policy.ListAuthorizationPoliciesResponse]: + r"""Return a callable for the list authorization policies method over gRPC. + + Lists AuthorizationPolicies in a given project and + location. + + Returns: + Callable[[~.ListAuthorizationPoliciesRequest], + ~.ListAuthorizationPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_authorization_policies' not in self._stubs: + self._stubs['list_authorization_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/ListAuthorizationPolicies', + request_serializer=authorization_policy.ListAuthorizationPoliciesRequest.serialize, + response_deserializer=authorization_policy.ListAuthorizationPoliciesResponse.deserialize, + ) + return self._stubs['list_authorization_policies'] + + @property + def get_authorization_policy(self) -> Callable[ + [authorization_policy.GetAuthorizationPolicyRequest], + authorization_policy.AuthorizationPolicy]: + r"""Return a callable for the get authorization policy method over gRPC. + + Gets details of a single AuthorizationPolicy. + + Returns: + Callable[[~.GetAuthorizationPolicyRequest], + ~.AuthorizationPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_authorization_policy' not in self._stubs: + self._stubs['get_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/GetAuthorizationPolicy', + request_serializer=authorization_policy.GetAuthorizationPolicyRequest.serialize, + response_deserializer=authorization_policy.AuthorizationPolicy.deserialize, + ) + return self._stubs['get_authorization_policy'] + + @property + def create_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.CreateAuthorizationPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the create authorization policy method over gRPC. + + Creates a new AuthorizationPolicy in a given project + and location. + + Returns: + Callable[[~.CreateAuthorizationPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_authorization_policy' not in self._stubs: + self._stubs['create_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/CreateAuthorizationPolicy', + request_serializer=gcn_authorization_policy.CreateAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_authorization_policy'] + + @property + def update_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the update authorization policy method over gRPC. + + Updates the parameters of a single + AuthorizationPolicy. + + Returns: + Callable[[~.UpdateAuthorizationPolicyRequest], + ~.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 'update_authorization_policy' not in self._stubs: + self._stubs['update_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateAuthorizationPolicy', + request_serializer=gcn_authorization_policy.UpdateAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_authorization_policy'] + + @property + def delete_authorization_policy(self) -> Callable[ + [authorization_policy.DeleteAuthorizationPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete authorization policy method over gRPC. + + Deletes a single AuthorizationPolicy. + + Returns: + Callable[[~.DeleteAuthorizationPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_authorization_policy' not in self._stubs: + self._stubs['delete_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteAuthorizationPolicy', + request_serializer=authorization_policy.DeleteAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_authorization_policy'] + + @property + def list_server_tls_policies(self) -> Callable[ + [server_tls_policy.ListServerTlsPoliciesRequest], + server_tls_policy.ListServerTlsPoliciesResponse]: + r"""Return a callable for the list server tls policies method over gRPC. + + Lists ServerTlsPolicies in a given project and + location. + + Returns: + Callable[[~.ListServerTlsPoliciesRequest], + ~.ListServerTlsPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_server_tls_policies' not in self._stubs: + self._stubs['list_server_tls_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/ListServerTlsPolicies', + request_serializer=server_tls_policy.ListServerTlsPoliciesRequest.serialize, + response_deserializer=server_tls_policy.ListServerTlsPoliciesResponse.deserialize, + ) + return self._stubs['list_server_tls_policies'] + + @property + def get_server_tls_policy(self) -> Callable[ + [server_tls_policy.GetServerTlsPolicyRequest], + server_tls_policy.ServerTlsPolicy]: + r"""Return a callable for the get server tls policy method over gRPC. + + Gets details of a single ServerTlsPolicy. + + Returns: + Callable[[~.GetServerTlsPolicyRequest], + ~.ServerTlsPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_server_tls_policy' not in self._stubs: + self._stubs['get_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/GetServerTlsPolicy', + request_serializer=server_tls_policy.GetServerTlsPolicyRequest.serialize, + response_deserializer=server_tls_policy.ServerTlsPolicy.deserialize, + ) + return self._stubs['get_server_tls_policy'] + + @property + def create_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.CreateServerTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the create server tls policy method over gRPC. + + Creates a new ServerTlsPolicy in a given project and + location. + + Returns: + Callable[[~.CreateServerTlsPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_server_tls_policy' not in self._stubs: + self._stubs['create_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/CreateServerTlsPolicy', + request_serializer=gcn_server_tls_policy.CreateServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_server_tls_policy'] + + @property + def update_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the update server tls policy method over gRPC. + + Updates the parameters of a single ServerTlsPolicy. + + Returns: + Callable[[~.UpdateServerTlsPolicyRequest], + ~.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 'update_server_tls_policy' not in self._stubs: + self._stubs['update_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateServerTlsPolicy', + request_serializer=gcn_server_tls_policy.UpdateServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_server_tls_policy'] + + @property + def delete_server_tls_policy(self) -> Callable[ + [server_tls_policy.DeleteServerTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete server tls policy method over gRPC. + + Deletes a single ServerTlsPolicy. + + Returns: + Callable[[~.DeleteServerTlsPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_server_tls_policy' not in self._stubs: + self._stubs['delete_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteServerTlsPolicy', + request_serializer=server_tls_policy.DeleteServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_server_tls_policy'] + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + client_tls_policy.ListClientTlsPoliciesResponse]: + r"""Return a callable for the list client tls policies method over gRPC. + + Lists ClientTlsPolicies in a given project and + location. + + Returns: + Callable[[~.ListClientTlsPoliciesRequest], + ~.ListClientTlsPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: + self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/ListClientTlsPolicies', + request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, + response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, + ) + return self._stubs['list_client_tls_policies'] + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + client_tls_policy.ClientTlsPolicy]: + r"""Return a callable for the get client tls policy method over gRPC. + + Gets details of a single ClientTlsPolicy. + + Returns: + Callable[[~.GetClientTlsPolicyRequest], + ~.ClientTlsPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: + self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/GetClientTlsPolicy', + request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, + response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, + ) + return self._stubs['get_client_tls_policy'] + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the create client tls policy method over gRPC. + + Creates a new ClientTlsPolicy in a given project and + location. + + Returns: + Callable[[~.CreateClientTlsPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_client_tls_policy' not in self._stubs: + self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/CreateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_client_tls_policy'] + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the update client tls policy method over gRPC. + + Updates the parameters of a single ClientTlsPolicy. + + Returns: + Callable[[~.UpdateClientTlsPolicyRequest], + ~.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 'update_client_tls_policy' not in self._stubs: + self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_client_tls_policy'] + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete client tls policy method over gRPC. + + Deletes a single ClientTlsPolicy. + + Returns: + Callable[[~.DeleteClientTlsPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_client_tls_policy' not in self._stubs: + self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteClientTlsPolicy', + request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_client_tls_policy'] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'NetworkSecurityGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc_asyncio.py new file mode 100644 index 000000000000..ddd1655d399a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc_asyncio.py @@ -0,0 +1,1069 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.types import authorization_policy +from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1.types import client_tls_policy +from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO +from .grpc import NetworkSecurityGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class NetworkSecurityGrpcAsyncIOTransport(NetworkSecurityTransport): + """gRPC AsyncIO backend transport for NetworkSecurity. + + Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_authorization_policies(self) -> Callable[ + [authorization_policy.ListAuthorizationPoliciesRequest], + Awaitable[authorization_policy.ListAuthorizationPoliciesResponse]]: + r"""Return a callable for the list authorization policies method over gRPC. + + Lists AuthorizationPolicies in a given project and + location. + + Returns: + Callable[[~.ListAuthorizationPoliciesRequest], + Awaitable[~.ListAuthorizationPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_authorization_policies' not in self._stubs: + self._stubs['list_authorization_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/ListAuthorizationPolicies', + request_serializer=authorization_policy.ListAuthorizationPoliciesRequest.serialize, + response_deserializer=authorization_policy.ListAuthorizationPoliciesResponse.deserialize, + ) + return self._stubs['list_authorization_policies'] + + @property + def get_authorization_policy(self) -> Callable[ + [authorization_policy.GetAuthorizationPolicyRequest], + Awaitable[authorization_policy.AuthorizationPolicy]]: + r"""Return a callable for the get authorization policy method over gRPC. + + Gets details of a single AuthorizationPolicy. + + Returns: + Callable[[~.GetAuthorizationPolicyRequest], + Awaitable[~.AuthorizationPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_authorization_policy' not in self._stubs: + self._stubs['get_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/GetAuthorizationPolicy', + request_serializer=authorization_policy.GetAuthorizationPolicyRequest.serialize, + response_deserializer=authorization_policy.AuthorizationPolicy.deserialize, + ) + return self._stubs['get_authorization_policy'] + + @property + def create_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.CreateAuthorizationPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create authorization policy method over gRPC. + + Creates a new AuthorizationPolicy in a given project + and location. + + Returns: + Callable[[~.CreateAuthorizationPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_authorization_policy' not in self._stubs: + self._stubs['create_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/CreateAuthorizationPolicy', + request_serializer=gcn_authorization_policy.CreateAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_authorization_policy'] + + @property + def update_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update authorization policy method over gRPC. + + Updates the parameters of a single + AuthorizationPolicy. + + Returns: + Callable[[~.UpdateAuthorizationPolicyRequest], + 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 'update_authorization_policy' not in self._stubs: + self._stubs['update_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateAuthorizationPolicy', + request_serializer=gcn_authorization_policy.UpdateAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_authorization_policy'] + + @property + def delete_authorization_policy(self) -> Callable[ + [authorization_policy.DeleteAuthorizationPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete authorization policy method over gRPC. + + Deletes a single AuthorizationPolicy. + + Returns: + Callable[[~.DeleteAuthorizationPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_authorization_policy' not in self._stubs: + self._stubs['delete_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteAuthorizationPolicy', + request_serializer=authorization_policy.DeleteAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_authorization_policy'] + + @property + def list_server_tls_policies(self) -> Callable[ + [server_tls_policy.ListServerTlsPoliciesRequest], + Awaitable[server_tls_policy.ListServerTlsPoliciesResponse]]: + r"""Return a callable for the list server tls policies method over gRPC. + + Lists ServerTlsPolicies in a given project and + location. + + Returns: + Callable[[~.ListServerTlsPoliciesRequest], + Awaitable[~.ListServerTlsPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_server_tls_policies' not in self._stubs: + self._stubs['list_server_tls_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/ListServerTlsPolicies', + request_serializer=server_tls_policy.ListServerTlsPoliciesRequest.serialize, + response_deserializer=server_tls_policy.ListServerTlsPoliciesResponse.deserialize, + ) + return self._stubs['list_server_tls_policies'] + + @property + def get_server_tls_policy(self) -> Callable[ + [server_tls_policy.GetServerTlsPolicyRequest], + Awaitable[server_tls_policy.ServerTlsPolicy]]: + r"""Return a callable for the get server tls policy method over gRPC. + + Gets details of a single ServerTlsPolicy. + + Returns: + Callable[[~.GetServerTlsPolicyRequest], + Awaitable[~.ServerTlsPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_server_tls_policy' not in self._stubs: + self._stubs['get_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/GetServerTlsPolicy', + request_serializer=server_tls_policy.GetServerTlsPolicyRequest.serialize, + response_deserializer=server_tls_policy.ServerTlsPolicy.deserialize, + ) + return self._stubs['get_server_tls_policy'] + + @property + def create_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.CreateServerTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create server tls policy method over gRPC. + + Creates a new ServerTlsPolicy in a given project and + location. + + Returns: + Callable[[~.CreateServerTlsPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_server_tls_policy' not in self._stubs: + self._stubs['create_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/CreateServerTlsPolicy', + request_serializer=gcn_server_tls_policy.CreateServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_server_tls_policy'] + + @property + def update_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update server tls policy method over gRPC. + + Updates the parameters of a single ServerTlsPolicy. + + Returns: + Callable[[~.UpdateServerTlsPolicyRequest], + 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 'update_server_tls_policy' not in self._stubs: + self._stubs['update_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateServerTlsPolicy', + request_serializer=gcn_server_tls_policy.UpdateServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_server_tls_policy'] + + @property + def delete_server_tls_policy(self) -> Callable[ + [server_tls_policy.DeleteServerTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete server tls policy method over gRPC. + + Deletes a single ServerTlsPolicy. + + Returns: + Callable[[~.DeleteServerTlsPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_server_tls_policy' not in self._stubs: + self._stubs['delete_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteServerTlsPolicy', + request_serializer=server_tls_policy.DeleteServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_server_tls_policy'] + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + Awaitable[client_tls_policy.ListClientTlsPoliciesResponse]]: + r"""Return a callable for the list client tls policies method over gRPC. + + Lists ClientTlsPolicies in a given project and + location. + + Returns: + Callable[[~.ListClientTlsPoliciesRequest], + Awaitable[~.ListClientTlsPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: + self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/ListClientTlsPolicies', + request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, + response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, + ) + return self._stubs['list_client_tls_policies'] + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + Awaitable[client_tls_policy.ClientTlsPolicy]]: + r"""Return a callable for the get client tls policy method over gRPC. + + Gets details of a single ClientTlsPolicy. + + Returns: + Callable[[~.GetClientTlsPolicyRequest], + Awaitable[~.ClientTlsPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: + self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/GetClientTlsPolicy', + request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, + response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, + ) + return self._stubs['get_client_tls_policy'] + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create client tls policy method over gRPC. + + Creates a new ClientTlsPolicy in a given project and + location. + + Returns: + Callable[[~.CreateClientTlsPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_client_tls_policy' not in self._stubs: + self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/CreateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_client_tls_policy'] + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update client tls policy method over gRPC. + + Updates the parameters of a single ClientTlsPolicy. + + Returns: + Callable[[~.UpdateClientTlsPolicyRequest], + 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 'update_client_tls_policy' not in self._stubs: + self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_client_tls_policy'] + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete client tls policy method over gRPC. + + Deletes a single ClientTlsPolicy. + + Returns: + Callable[[~.DeleteClientTlsPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_client_tls_policy' not in self._stubs: + self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteClientTlsPolicy', + request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_client_tls_policy'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_authorization_policies: self._wrap_method( + self.list_authorization_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_authorization_policy: self._wrap_method( + self.get_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_authorization_policy: self._wrap_method( + self.create_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_authorization_policy: self._wrap_method( + self.update_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_authorization_policy: self._wrap_method( + self.delete_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_server_tls_policies: self._wrap_method( + self.list_server_tls_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_server_tls_policy: self._wrap_method( + self.get_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_server_tls_policy: self._wrap_method( + self.create_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_server_tls_policy: self._wrap_method( + self.update_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_server_tls_policy: self._wrap_method( + self.delete_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_client_tls_policies: self._wrap_method( + self.list_client_tls_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_client_tls_policy: self._wrap_method( + self.get_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_client_tls_policy: self._wrap_method( + self.create_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_client_tls_policy: self._wrap_method( + self.update_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_client_tls_policy: self._wrap_method( + self.delete_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'NetworkSecurityGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest.py new file mode 100644 index 000000000000..9f69f839923d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest.py @@ -0,0 +1,4105 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 +import google.protobuf + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.network_security_v1.types import authorization_policy +from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1.types import client_tls_policy +from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseNetworkSecurityRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class NetworkSecurityRestInterceptor: + """Interceptor for NetworkSecurity. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the NetworkSecurityRestTransport. + + .. code-block:: python + class MyCustomNetworkSecurityInterceptor(NetworkSecurityRestInterceptor): + def pre_create_authorization_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_authorization_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_client_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_client_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_server_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_server_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_authorization_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_authorization_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_client_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_client_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_server_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_server_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_authorization_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_authorization_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_client_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_client_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_server_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_server_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_authorization_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_authorization_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_client_tls_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_client_tls_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_server_tls_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_server_tls_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_authorization_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_authorization_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_client_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_client_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_server_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_server_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = NetworkSecurityRestTransport(interceptor=MyCustomNetworkSecurityInterceptor()) + client = NetworkSecurityClient(transport=transport) + + + """ + def pre_create_authorization_policy(self, request: gcn_authorization_policy.CreateAuthorizationPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_authorization_policy.CreateAuthorizationPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_authorization_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_create_authorization_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_authorization_policy + + DEPRECATED. Please use the `post_create_authorization_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_create_authorization_policy` interceptor runs + before the `post_create_authorization_policy_with_metadata` interceptor. + """ + return response + + def post_create_authorization_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_authorization_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_create_authorization_policy_with_metadata` + interceptor in new development instead of the `post_create_authorization_policy` interceptor. + When both interceptors are used, this `post_create_authorization_policy_with_metadata` interceptor runs after the + `post_create_authorization_policy` interceptor. The (possibly modified) response returned by + `post_create_authorization_policy` will be passed to + `post_create_authorization_policy_with_metadata`. + """ + return response, metadata + + def pre_create_client_tls_policy(self, request: gcn_client_tls_policy.CreateClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_client_tls_policy.CreateClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_client_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_create_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_client_tls_policy + + DEPRECATED. Please use the `post_create_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_create_client_tls_policy` interceptor runs + before the `post_create_client_tls_policy_with_metadata` interceptor. + """ + return response + + def post_create_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_create_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_create_client_tls_policy` interceptor. + When both interceptors are used, this `post_create_client_tls_policy_with_metadata` interceptor runs after the + `post_create_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_create_client_tls_policy` will be passed to + `post_create_client_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_create_server_tls_policy(self, request: gcn_server_tls_policy.CreateServerTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_server_tls_policy.CreateServerTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_server_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_create_server_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_server_tls_policy + + DEPRECATED. Please use the `post_create_server_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_create_server_tls_policy` interceptor runs + before the `post_create_server_tls_policy_with_metadata` interceptor. + """ + return response + + def post_create_server_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_server_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_create_server_tls_policy_with_metadata` + interceptor in new development instead of the `post_create_server_tls_policy` interceptor. + When both interceptors are used, this `post_create_server_tls_policy_with_metadata` interceptor runs after the + `post_create_server_tls_policy` interceptor. The (possibly modified) response returned by + `post_create_server_tls_policy` will be passed to + `post_create_server_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_authorization_policy(self, request: authorization_policy.DeleteAuthorizationPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[authorization_policy.DeleteAuthorizationPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_authorization_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_delete_authorization_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_authorization_policy + + DEPRECATED. Please use the `post_delete_authorization_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_delete_authorization_policy` interceptor runs + before the `post_delete_authorization_policy_with_metadata` interceptor. + """ + return response + + def post_delete_authorization_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_authorization_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_delete_authorization_policy_with_metadata` + interceptor in new development instead of the `post_delete_authorization_policy` interceptor. + When both interceptors are used, this `post_delete_authorization_policy_with_metadata` interceptor runs after the + `post_delete_authorization_policy` interceptor. The (possibly modified) response returned by + `post_delete_authorization_policy` will be passed to + `post_delete_authorization_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_client_tls_policy(self, request: client_tls_policy.DeleteClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.DeleteClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_client_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_delete_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_client_tls_policy + + DEPRECATED. Please use the `post_delete_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_delete_client_tls_policy` interceptor runs + before the `post_delete_client_tls_policy_with_metadata` interceptor. + """ + return response + + def post_delete_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_delete_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_delete_client_tls_policy` interceptor. + When both interceptors are used, this `post_delete_client_tls_policy_with_metadata` interceptor runs after the + `post_delete_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_delete_client_tls_policy` will be passed to + `post_delete_client_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_server_tls_policy(self, request: server_tls_policy.DeleteServerTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[server_tls_policy.DeleteServerTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_server_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_delete_server_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_server_tls_policy + + DEPRECATED. Please use the `post_delete_server_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_delete_server_tls_policy` interceptor runs + before the `post_delete_server_tls_policy_with_metadata` interceptor. + """ + return response + + def post_delete_server_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_server_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_delete_server_tls_policy_with_metadata` + interceptor in new development instead of the `post_delete_server_tls_policy` interceptor. + When both interceptors are used, this `post_delete_server_tls_policy_with_metadata` interceptor runs after the + `post_delete_server_tls_policy` interceptor. The (possibly modified) response returned by + `post_delete_server_tls_policy` will be passed to + `post_delete_server_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_get_authorization_policy(self, request: authorization_policy.GetAuthorizationPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[authorization_policy.GetAuthorizationPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_authorization_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_get_authorization_policy(self, response: authorization_policy.AuthorizationPolicy) -> authorization_policy.AuthorizationPolicy: + """Post-rpc interceptor for get_authorization_policy + + DEPRECATED. Please use the `post_get_authorization_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_get_authorization_policy` interceptor runs + before the `post_get_authorization_policy_with_metadata` interceptor. + """ + return response + + def post_get_authorization_policy_with_metadata(self, response: authorization_policy.AuthorizationPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[authorization_policy.AuthorizationPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_authorization_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_get_authorization_policy_with_metadata` + interceptor in new development instead of the `post_get_authorization_policy` interceptor. + When both interceptors are used, this `post_get_authorization_policy_with_metadata` interceptor runs after the + `post_get_authorization_policy` interceptor. The (possibly modified) response returned by + `post_get_authorization_policy` will be passed to + `post_get_authorization_policy_with_metadata`. + """ + return response, metadata + + def pre_get_client_tls_policy(self, request: client_tls_policy.GetClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.GetClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_client_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_get_client_tls_policy(self, response: client_tls_policy.ClientTlsPolicy) -> client_tls_policy.ClientTlsPolicy: + """Post-rpc interceptor for get_client_tls_policy + + DEPRECATED. Please use the `post_get_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_get_client_tls_policy` interceptor runs + before the `post_get_client_tls_policy_with_metadata` interceptor. + """ + return response + + def post_get_client_tls_policy_with_metadata(self, response: client_tls_policy.ClientTlsPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ClientTlsPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_get_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_get_client_tls_policy` interceptor. + When both interceptors are used, this `post_get_client_tls_policy_with_metadata` interceptor runs after the + `post_get_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_get_client_tls_policy` will be passed to + `post_get_client_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_get_server_tls_policy(self, request: server_tls_policy.GetServerTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[server_tls_policy.GetServerTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_server_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_get_server_tls_policy(self, response: server_tls_policy.ServerTlsPolicy) -> server_tls_policy.ServerTlsPolicy: + """Post-rpc interceptor for get_server_tls_policy + + DEPRECATED. Please use the `post_get_server_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_get_server_tls_policy` interceptor runs + before the `post_get_server_tls_policy_with_metadata` interceptor. + """ + return response + + def post_get_server_tls_policy_with_metadata(self, response: server_tls_policy.ServerTlsPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[server_tls_policy.ServerTlsPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_server_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_get_server_tls_policy_with_metadata` + interceptor in new development instead of the `post_get_server_tls_policy` interceptor. + When both interceptors are used, this `post_get_server_tls_policy_with_metadata` interceptor runs after the + `post_get_server_tls_policy` interceptor. The (possibly modified) response returned by + `post_get_server_tls_policy` will be passed to + `post_get_server_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_list_authorization_policies(self, request: authorization_policy.ListAuthorizationPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[authorization_policy.ListAuthorizationPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_authorization_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_list_authorization_policies(self, response: authorization_policy.ListAuthorizationPoliciesResponse) -> authorization_policy.ListAuthorizationPoliciesResponse: + """Post-rpc interceptor for list_authorization_policies + + DEPRECATED. Please use the `post_list_authorization_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_list_authorization_policies` interceptor runs + before the `post_list_authorization_policies_with_metadata` interceptor. + """ + return response + + def post_list_authorization_policies_with_metadata(self, response: authorization_policy.ListAuthorizationPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[authorization_policy.ListAuthorizationPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_authorization_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_list_authorization_policies_with_metadata` + interceptor in new development instead of the `post_list_authorization_policies` interceptor. + When both interceptors are used, this `post_list_authorization_policies_with_metadata` interceptor runs after the + `post_list_authorization_policies` interceptor. The (possibly modified) response returned by + `post_list_authorization_policies` will be passed to + `post_list_authorization_policies_with_metadata`. + """ + return response, metadata + + def pre_list_client_tls_policies(self, request: client_tls_policy.ListClientTlsPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ListClientTlsPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_client_tls_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_list_client_tls_policies(self, response: client_tls_policy.ListClientTlsPoliciesResponse) -> client_tls_policy.ListClientTlsPoliciesResponse: + """Post-rpc interceptor for list_client_tls_policies + + DEPRECATED. Please use the `post_list_client_tls_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_list_client_tls_policies` interceptor runs + before the `post_list_client_tls_policies_with_metadata` interceptor. + """ + return response + + def post_list_client_tls_policies_with_metadata(self, response: client_tls_policy.ListClientTlsPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ListClientTlsPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_client_tls_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_list_client_tls_policies_with_metadata` + interceptor in new development instead of the `post_list_client_tls_policies` interceptor. + When both interceptors are used, this `post_list_client_tls_policies_with_metadata` interceptor runs after the + `post_list_client_tls_policies` interceptor. The (possibly modified) response returned by + `post_list_client_tls_policies` will be passed to + `post_list_client_tls_policies_with_metadata`. + """ + return response, metadata + + def pre_list_server_tls_policies(self, request: server_tls_policy.ListServerTlsPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[server_tls_policy.ListServerTlsPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_server_tls_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_list_server_tls_policies(self, response: server_tls_policy.ListServerTlsPoliciesResponse) -> server_tls_policy.ListServerTlsPoliciesResponse: + """Post-rpc interceptor for list_server_tls_policies + + DEPRECATED. Please use the `post_list_server_tls_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_list_server_tls_policies` interceptor runs + before the `post_list_server_tls_policies_with_metadata` interceptor. + """ + return response + + def post_list_server_tls_policies_with_metadata(self, response: server_tls_policy.ListServerTlsPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[server_tls_policy.ListServerTlsPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_server_tls_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_list_server_tls_policies_with_metadata` + interceptor in new development instead of the `post_list_server_tls_policies` interceptor. + When both interceptors are used, this `post_list_server_tls_policies_with_metadata` interceptor runs after the + `post_list_server_tls_policies` interceptor. The (possibly modified) response returned by + `post_list_server_tls_policies` will be passed to + `post_list_server_tls_policies_with_metadata`. + """ + return response, metadata + + def pre_update_authorization_policy(self, request: gcn_authorization_policy.UpdateAuthorizationPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_authorization_policy.UpdateAuthorizationPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_authorization_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_update_authorization_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_authorization_policy + + DEPRECATED. Please use the `post_update_authorization_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_update_authorization_policy` interceptor runs + before the `post_update_authorization_policy_with_metadata` interceptor. + """ + return response + + def post_update_authorization_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_authorization_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_update_authorization_policy_with_metadata` + interceptor in new development instead of the `post_update_authorization_policy` interceptor. + When both interceptors are used, this `post_update_authorization_policy_with_metadata` interceptor runs after the + `post_update_authorization_policy` interceptor. The (possibly modified) response returned by + `post_update_authorization_policy` will be passed to + `post_update_authorization_policy_with_metadata`. + """ + return response, metadata + + def pre_update_client_tls_policy(self, request: gcn_client_tls_policy.UpdateClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_client_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_update_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_client_tls_policy + + DEPRECATED. Please use the `post_update_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_update_client_tls_policy` interceptor runs + before the `post_update_client_tls_policy_with_metadata` interceptor. + """ + return response + + def post_update_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_update_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_update_client_tls_policy` interceptor. + When both interceptors are used, this `post_update_client_tls_policy_with_metadata` interceptor runs after the + `post_update_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_update_client_tls_policy` will be passed to + `post_update_client_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_update_server_tls_policy(self, request: gcn_server_tls_policy.UpdateServerTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_server_tls_policy.UpdateServerTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_server_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_update_server_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_server_tls_policy + + DEPRECATED. Please use the `post_update_server_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_update_server_tls_policy` interceptor runs + before the `post_update_server_tls_policy_with_metadata` interceptor. + """ + return response + + def post_update_server_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_server_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_update_server_tls_policy_with_metadata` + interceptor in new development instead of the `post_update_server_tls_policy` interceptor. + When both interceptors are used, this `post_update_server_tls_policy_with_metadata` interceptor runs after the + `post_update_server_tls_policy` interceptor. The (possibly modified) response returned by + `post_update_server_tls_policy` will be passed to + `post_update_server_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class NetworkSecurityRestStub: + _session: AuthorizedSession + _host: str + _interceptor: NetworkSecurityRestInterceptor + + +class NetworkSecurityRestTransport(_BaseNetworkSecurityRestTransport): + """REST backend synchronous transport for NetworkSecurity. + + Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[NetworkSecurityRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or NetworkSecurityRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateAuthorizationPolicy(_BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.CreateAuthorizationPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_authorization_policy.CreateAuthorizationPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create authorization + policy method over HTTP. + + Args: + request (~.gcn_authorization_policy.CreateAuthorizationPolicyRequest): + The request object. Request used by the + CreateAuthorizationPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_http_options() + + request, metadata = self._interceptor.pre_create_authorization_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.CreateAuthorizationPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "CreateAuthorizationPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._CreateAuthorizationPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_authorization_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_authorization_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.create_authorization_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "CreateAuthorizationPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.CreateClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_client_tls_policy.CreateClientTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create client tls policy method over HTTP. + + Args: + request (~.gcn_client_tls_policy.CreateClientTlsPolicyRequest): + The request object. Request used by the + CreateClientTlsPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_create_client_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.CreateClientTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "CreateClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._CreateClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_client_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.create_client_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "CreateClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateServerTlsPolicy(_BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.CreateServerTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_server_tls_policy.CreateServerTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create server tls policy method over HTTP. + + Args: + request (~.gcn_server_tls_policy.CreateServerTlsPolicyRequest): + The request object. Request used by the + CreateServerTlsPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_create_server_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.CreateServerTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "CreateServerTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._CreateServerTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_server_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_server_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.create_server_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "CreateServerTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAuthorizationPolicy(_BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.DeleteAuthorizationPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: authorization_policy.DeleteAuthorizationPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete authorization + policy method over HTTP. + + Args: + request (~.authorization_policy.DeleteAuthorizationPolicyRequest): + The request object. Request used by the + DeleteAuthorizationPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_http_options() + + request, metadata = self._interceptor.pre_delete_authorization_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.DeleteAuthorizationPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "DeleteAuthorizationPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._DeleteAuthorizationPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_authorization_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_authorization_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.delete_authorization_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "DeleteAuthorizationPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.DeleteClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: client_tls_policy.DeleteClientTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete client tls policy method over HTTP. + + Args: + request (~.client_tls_policy.DeleteClientTlsPolicyRequest): + The request object. Request used by the + DeleteClientTlsPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_delete_client_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.DeleteClientTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "DeleteClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._DeleteClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_client_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.delete_client_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "DeleteClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteServerTlsPolicy(_BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.DeleteServerTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: server_tls_policy.DeleteServerTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete server tls policy method over HTTP. + + Args: + request (~.server_tls_policy.DeleteServerTlsPolicyRequest): + The request object. Request used by the + DeleteServerTlsPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_delete_server_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.DeleteServerTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "DeleteServerTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._DeleteServerTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_server_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_server_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.delete_server_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "DeleteServerTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAuthorizationPolicy(_BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetAuthorizationPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: authorization_policy.GetAuthorizationPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> authorization_policy.AuthorizationPolicy: + r"""Call the get authorization policy method over HTTP. + + Args: + request (~.authorization_policy.GetAuthorizationPolicyRequest): + The request object. Request used by the + GetAuthorizationPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.authorization_policy.AuthorizationPolicy: + AuthorizationPolicy is a resource + that specifies how a server should + authorize incoming connections. This + resource in itself does not change the + configuration unless it's attached to a + target https proxy or endpoint config + selector resource. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_authorization_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetAuthorizationPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetAuthorizationPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._GetAuthorizationPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = authorization_policy.AuthorizationPolicy() + pb_resp = authorization_policy.AuthorizationPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_authorization_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_authorization_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = authorization_policy.AuthorizationPolicy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.get_authorization_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetAuthorizationPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: client_tls_policy.GetClientTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> client_tls_policy.ClientTlsPolicy: + r"""Call the get client tls policy method over HTTP. + + Args: + request (~.client_tls_policy.GetClientTlsPolicyRequest): + The request object. Request used by the + GetClientTlsPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.client_tls_policy.ClientTlsPolicy: + ClientTlsPolicy is a resource that + specifies how a client should + authenticate connections to backends of + a service. This resource itself does not + affect configuration unless it is + attached to a backend service resource. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_client_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetClientTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._GetClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = client_tls_policy.ClientTlsPolicy() + pb_resp = client_tls_policy.ClientTlsPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_client_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = client_tls_policy.ClientTlsPolicy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.get_client_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetServerTlsPolicy(_BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetServerTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: server_tls_policy.GetServerTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> server_tls_policy.ServerTlsPolicy: + r"""Call the get server tls policy method over HTTP. + + Args: + request (~.server_tls_policy.GetServerTlsPolicyRequest): + The request object. Request used by the + GetServerTlsPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.server_tls_policy.ServerTlsPolicy: + ServerTlsPolicy is a resource that + specifies how a server should + authenticate incoming requests. This + resource itself does not affect + configuration unless it is attached to a + target https proxy or endpoint config + selector resource. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_server_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetServerTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetServerTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._GetServerTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = server_tls_policy.ServerTlsPolicy() + pb_resp = server_tls_policy.ServerTlsPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_server_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_server_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = server_tls_policy.ServerTlsPolicy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.get_server_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetServerTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAuthorizationPolicies(_BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.ListAuthorizationPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: authorization_policy.ListAuthorizationPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> authorization_policy.ListAuthorizationPoliciesResponse: + r"""Call the list authorization + policies method over HTTP. + + Args: + request (~.authorization_policy.ListAuthorizationPoliciesRequest): + The request object. Request used with the + ListAuthorizationPolicies method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.authorization_policy.ListAuthorizationPoliciesResponse: + Response returned by the + ListAuthorizationPolicies method. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_http_options() + + request, metadata = self._interceptor.pre_list_authorization_policies(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.ListAuthorizationPolicies", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "ListAuthorizationPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._ListAuthorizationPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = authorization_policy.ListAuthorizationPoliciesResponse() + pb_resp = authorization_policy.ListAuthorizationPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_authorization_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_authorization_policies_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = authorization_policy.ListAuthorizationPoliciesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.list_authorization_policies", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "ListAuthorizationPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListClientTlsPolicies(_BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.ListClientTlsPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: client_tls_policy.ListClientTlsPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> client_tls_policy.ListClientTlsPoliciesResponse: + r"""Call the list client tls policies method over HTTP. + + Args: + request (~.client_tls_policy.ListClientTlsPoliciesRequest): + The request object. Request used by the + ListClientTlsPolicies method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.client_tls_policy.ListClientTlsPoliciesResponse: + Response returned by the + ListClientTlsPolicies method. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_http_options() + + request, metadata = self._interceptor.pre_list_client_tls_policies(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.ListClientTlsPolicies", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "ListClientTlsPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._ListClientTlsPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = client_tls_policy.ListClientTlsPoliciesResponse() + pb_resp = client_tls_policy.ListClientTlsPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_client_tls_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_client_tls_policies_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = client_tls_policy.ListClientTlsPoliciesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.list_client_tls_policies", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "ListClientTlsPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListServerTlsPolicies(_BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.ListServerTlsPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: server_tls_policy.ListServerTlsPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> server_tls_policy.ListServerTlsPoliciesResponse: + r"""Call the list server tls policies method over HTTP. + + Args: + request (~.server_tls_policy.ListServerTlsPoliciesRequest): + The request object. Request used by the + ListServerTlsPolicies method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.server_tls_policy.ListServerTlsPoliciesResponse: + Response returned by the + ListServerTlsPolicies method. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_http_options() + + request, metadata = self._interceptor.pre_list_server_tls_policies(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.ListServerTlsPolicies", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "ListServerTlsPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._ListServerTlsPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = server_tls_policy.ListServerTlsPoliciesResponse() + pb_resp = server_tls_policy.ListServerTlsPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_server_tls_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_server_tls_policies_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = server_tls_policy.ListServerTlsPoliciesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.list_server_tls_policies", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "ListServerTlsPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAuthorizationPolicy(_BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.UpdateAuthorizationPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_authorization_policy.UpdateAuthorizationPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update authorization + policy method over HTTP. + + Args: + request (~.gcn_authorization_policy.UpdateAuthorizationPolicyRequest): + The request object. Request used by the + UpdateAuthorizationPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_http_options() + + request, metadata = self._interceptor.pre_update_authorization_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.UpdateAuthorizationPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "UpdateAuthorizationPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._UpdateAuthorizationPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_authorization_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_authorization_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.update_authorization_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "UpdateAuthorizationPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.UpdateClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_client_tls_policy.UpdateClientTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update client tls policy method over HTTP. + + Args: + request (~.gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + The request object. Request used by UpdateClientTlsPolicy + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_update_client_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.UpdateClientTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "UpdateClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._UpdateClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_client_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.update_client_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "UpdateClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateServerTlsPolicy(_BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.UpdateServerTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_server_tls_policy.UpdateServerTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update server tls policy method over HTTP. + + Args: + request (~.gcn_server_tls_policy.UpdateServerTlsPolicyRequest): + The request object. Request used by UpdateServerTlsPolicy + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_update_server_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.UpdateServerTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "UpdateServerTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._UpdateServerTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_server_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_server_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.update_server_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "UpdateServerTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.CreateAuthorizationPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAuthorizationPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.CreateServerTlsPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateServerTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_authorization_policy(self) -> Callable[ + [authorization_policy.DeleteAuthorizationPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAuthorizationPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_server_tls_policy(self) -> Callable[ + [server_tls_policy.DeleteServerTlsPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteServerTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_authorization_policy(self) -> Callable[ + [authorization_policy.GetAuthorizationPolicyRequest], + authorization_policy.AuthorizationPolicy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAuthorizationPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + client_tls_policy.ClientTlsPolicy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_server_tls_policy(self) -> Callable[ + [server_tls_policy.GetServerTlsPolicyRequest], + server_tls_policy.ServerTlsPolicy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetServerTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_authorization_policies(self) -> Callable[ + [authorization_policy.ListAuthorizationPoliciesRequest], + authorization_policy.ListAuthorizationPoliciesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAuthorizationPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + client_tls_policy.ListClientTlsPoliciesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListClientTlsPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_server_tls_policies(self) -> Callable[ + [server_tls_policy.ListServerTlsPoliciesRequest], + server_tls_policy.ListServerTlsPoliciesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListServerTlsPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAuthorizationPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateServerTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseNetworkSecurityRestTransport._BaseGetLocation, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_http_options() + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetLocation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.GetLocation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseNetworkSecurityRestTransport._BaseListLocations, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseListLocations._get_http_options() + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.ListLocations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.ListLocations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseNetworkSecurityRestTransport._BaseGetIamPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.GetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseNetworkSecurityRestTransport._BaseSetIamPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.SetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.SetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseNetworkSecurityRestTransport._BaseTestIamPermissions, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.TestIamPermissions", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.TestIamPermissions", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseNetworkSecurityRestTransport._BaseCancelOperation, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.CancelOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseNetworkSecurityRestTransport._BaseDeleteOperation, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseNetworkSecurityRestTransport._BaseGetOperation, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseNetworkSecurityRestTransport._BaseListOperations, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.ListOperations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'NetworkSecurityRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest_base.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest_base.py new file mode 100644 index 000000000000..9742866a51ed --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest_base.py @@ -0,0 +1,1036 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.network_security_v1.types import authorization_policy +from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1.types import client_tls_policy +from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseNetworkSecurityRestTransport(NetworkSecurityTransport): + """Base REST backend transport for NetworkSecurity. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[Any]): 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. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseCreateAuthorizationPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "authorizationPolicyId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/authorizationPolicies', + 'body': 'authorization_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_authorization_policy.CreateAuthorizationPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clientTlsPolicyId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/clientTlsPolicies', + 'body': 'client_tls_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateServerTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "serverTlsPolicyId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/serverTlsPolicies', + 'body': 'server_tls_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_server_tls_policy.CreateServerTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteAuthorizationPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/authorizationPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = authorization_policy.DeleteAuthorizationPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/clientTlsPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = client_tls_policy.DeleteClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteServerTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/serverTlsPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = server_tls_policy.DeleteServerTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAuthorizationPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/authorizationPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = authorization_policy.GetAuthorizationPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/clientTlsPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = client_tls_policy.GetClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetServerTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/serverTlsPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = server_tls_policy.GetServerTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAuthorizationPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/authorizationPolicies', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = authorization_policy.ListAuthorizationPoliciesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListClientTlsPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/clientTlsPolicies', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = client_tls_policy.ListClientTlsPoliciesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListServerTlsPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/serverTlsPolicies', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = server_tls_policy.ListServerTlsPoliciesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAuthorizationPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{authorization_policy.name=projects/*/locations/*/authorizationPolicies/*}', + 'body': 'authorization_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}', + 'body': 'client_tls_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateServerTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{server_tls_policy.name=projects/*/locations/*/serverTlsPolicies/*}', + 'body': 'server_tls_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}/operations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseNetworkSecurityRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py new file mode 100644 index 000000000000..a565010ab274 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 OrganizationAddressGroupServiceClient +from .async_client import OrganizationAddressGroupServiceAsyncClient + +__all__ = ( + 'OrganizationAddressGroupServiceClient', + 'OrganizationAddressGroupServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py new file mode 100644 index 000000000000..652742603b03 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py @@ -0,0 +1,2046 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.network_security_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.services.organization_address_group_service import pagers +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import common +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import OrganizationAddressGroupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import OrganizationAddressGroupServiceGrpcAsyncIOTransport +from .client import OrganizationAddressGroupServiceClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class OrganizationAddressGroupServiceAsyncClient: + """Organization AddressGroup is created under organization. + Requests against Organization AddressGroup will use project from + request credential for activation/quota/visibility check. + """ + + _client: OrganizationAddressGroupServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = OrganizationAddressGroupServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE + + address_group_path = staticmethod(OrganizationAddressGroupServiceClient.address_group_path) + parse_address_group_path = staticmethod(OrganizationAddressGroupServiceClient.parse_address_group_path) + common_billing_account_path = staticmethod(OrganizationAddressGroupServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(OrganizationAddressGroupServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(OrganizationAddressGroupServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(OrganizationAddressGroupServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(OrganizationAddressGroupServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(OrganizationAddressGroupServiceClient.parse_common_organization_path) + common_project_path = staticmethod(OrganizationAddressGroupServiceClient.common_project_path) + parse_common_project_path = staticmethod(OrganizationAddressGroupServiceClient.parse_common_project_path) + common_location_path = staticmethod(OrganizationAddressGroupServiceClient.common_location_path) + parse_common_location_path = staticmethod(OrganizationAddressGroupServiceClient.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: + OrganizationAddressGroupServiceAsyncClient: The constructed client. + """ + return OrganizationAddressGroupServiceClient.from_service_account_info.__func__(OrganizationAddressGroupServiceAsyncClient, 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: + OrganizationAddressGroupServiceAsyncClient: The constructed client. + """ + return OrganizationAddressGroupServiceClient.from_service_account_file.__func__(OrganizationAddressGroupServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return OrganizationAddressGroupServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> OrganizationAddressGroupServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OrganizationAddressGroupServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = OrganizationAddressGroupServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, OrganizationAddressGroupServiceTransport, Callable[..., OrganizationAddressGroupServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the organization address group service async 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 (Optional[Union[str,OrganizationAddressGroupServiceTransport,Callable[..., OrganizationAddressGroupServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the OrganizationAddressGroupServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = OrganizationAddressGroupServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient`.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "credentialsType": None, + } + ) + + async def list_address_groups(self, + request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupsAsyncPager: + r"""Lists address groups in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_address_groups(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_address_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListAddressGroupsRequest, dict]]): + The request object. Request used with the + ListAddressGroups method. + parent (:class:`str`): + Required. The project and location from which the + AddressGroups should be listed, specified in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsAsyncPager: + Response returned by the + ListAddressGroups method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.ListAddressGroupsRequest): + request = address_group.ListAddressGroupsRequest(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._client._transport._wrapped_methods[self._client._transport.list_address_groups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAddressGroupsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_address_group(self, + request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.AddressGroup: + r"""Gets details of a single address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_get_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetAddressGroupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_address_group(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.GetAddressGroupRequest, dict]]): + The request object. Request used by the GetAddressGroup + method. + name (:class:`str`): + Required. A name of the AddressGroup to get. Must be in + the format + ``projects/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.types.AddressGroup: + AddressGroup is a resource that + specifies how a collection of IP/DNS + used in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.GetAddressGroupRequest): + request = address_group.GetAddressGroupRequest(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._client._transport._wrapped_methods[self._client._transport.get_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_address_group(self, + request: Optional[Union[gcn_address_group.CreateAddressGroupRequest, dict]] = None, + *, + parent: Optional[str] = None, + address_group: Optional[gcn_address_group.AddressGroup] = None, + address_group_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new address group in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_create_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.CreateAddressGroupRequest( + parent="parent_value", + address_group_id="address_group_id_value", + address_group=address_group, + ) + + # Make the request + operation = client.create_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CreateAddressGroupRequest, dict]]): + The request object. Request used by the + CreateAddressGroup method. + parent (:class:`str`): + Required. The parent resource of the AddressGroup. Must + be in the format ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + address_group (:class:`google.cloud.network_security_v1.types.AddressGroup`): + Required. AddressGroup resource to be + created. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + address_group_id (:class:`str`): + Required. Short name of the AddressGroup resource to be + created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "authz_policy". + + This corresponds to the ``address_group_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, address_group, address_group_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.CreateAddressGroupRequest): + request = gcn_address_group.CreateAddressGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if address_group is not None: + request.address_group = address_group + if address_group_id is not None: + request.address_group_id = address_group_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_address_group] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_address_group(self, + request: Optional[Union[gcn_address_group.UpdateAddressGroupRequest, dict]] = None, + *, + address_group: Optional[gcn_address_group.AddressGroup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates parameters of an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_update_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.UpdateAddressGroupRequest( + address_group=address_group, + ) + + # Make the request + operation = client.update_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.UpdateAddressGroupRequest, dict]]): + The request object. Request used by the + UpdateAddressGroup method. + address_group (:class:`google.cloud.network_security_v1.types.AddressGroup`): + Required. Updated AddressGroup + resource. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the AddressGroup resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.UpdateAddressGroupRequest): + request = gcn_address_group.UpdateAddressGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group.name", request.address_group.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def add_address_group_items(self, + request: Optional[Union[gcn_address_group.AddAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Adds items to an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_add_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.AddAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.add_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.AddAddressGroupItemsRequest, dict]]): + The request object. Request used by the + AddAddressGroupItems method. + address_group (:class:`str`): + Required. A name of the AddressGroup to add items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + items (:class:`MutableSequence[str]`): + Required. List of items to add. + This corresponds to the ``items`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, items] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.AddAddressGroupItemsRequest): + request = gcn_address_group.AddAddressGroupItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if items: + request.items.extend(items) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.add_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def remove_address_group_items(self, + request: Optional[Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Removes items from an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_remove_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.RemoveAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.remove_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest, dict]]): + The request object. Request used by the + RemoveAddressGroupItems method. + address_group (:class:`str`): + Required. A name of the AddressGroup to remove items + from. Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + items (:class:`MutableSequence[str]`): + Required. List of items to remove. + This corresponds to the ``items`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, items] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.RemoveAddressGroupItemsRequest): + request = gcn_address_group.RemoveAddressGroupItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if items: + request.items.extend(items) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.remove_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def clone_address_group_items(self, + request: Optional[Union[gcn_address_group.CloneAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + source_address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Clones items from one address group to another. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_clone_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CloneAddressGroupItemsRequest( + address_group="address_group_value", + source_address_group="source_address_group_value", + ) + + # Make the request + operation = client.clone_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest, dict]]): + The request object. Request used by the + CloneAddressGroupItems method. + address_group (:class:`str`): + Required. A name of the AddressGroup to clone items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source_address_group (:class:`str`): + Required. Source address group to + clone items from. + + This corresponds to the ``source_address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, source_address_group] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.CloneAddressGroupItemsRequest): + request = gcn_address_group.CloneAddressGroupItemsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if source_address_group is not None: + request.source_address_group = source_address_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.clone_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_address_group(self, + request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_delete_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAddressGroupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.DeleteAddressGroupRequest, dict]]): + The request object. Request used by the + DeleteAddressGroup method. + name (:class:`str`): + Required. A name of the AddressGroup to delete. Must be + in the format + ``projects/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.DeleteAddressGroupRequest): + request = address_group.DeleteAddressGroupRequest(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._client._transport._wrapped_methods[self._client._transport.delete_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_address_group_references(self, + request: Optional[Union[gcn_address_group.ListAddressGroupReferencesRequest, dict]] = None, + *, + address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupReferencesAsyncPager: + r"""Lists references of an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + async def sample_list_address_group_references(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupReferencesRequest( + address_group="address_group_value", + ) + + # Make the request + page_result = client.list_address_group_references(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest, dict]]): + The request object. Request used by the + ListAddressGroupReferences method. + address_group (:class:`str`): + Required. A name of the AddressGroup to clone items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesAsyncPager: + Response of the + ListAddressGroupReferences method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.ListAddressGroupReferencesRequest): + request = gcn_address_group.ListAddressGroupReferencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_address_group_references] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAddressGroupReferencesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "OrganizationAddressGroupServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "OrganizationAddressGroupServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/client.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/client.py new file mode 100644 index 000000000000..04bdc599ac71 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/client.py @@ -0,0 +1,2421 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.network_security_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.services.organization_address_group_service import pagers +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import common +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import OrganizationAddressGroupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import OrganizationAddressGroupServiceGrpcTransport +from .transports.grpc_asyncio import OrganizationAddressGroupServiceGrpcAsyncIOTransport +from .transports.rest import OrganizationAddressGroupServiceRestTransport + + +class OrganizationAddressGroupServiceClientMeta(type): + """Metaclass for the OrganizationAddressGroupService 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[OrganizationAddressGroupServiceTransport]] + _transport_registry["grpc"] = OrganizationAddressGroupServiceGrpcTransport + _transport_registry["grpc_asyncio"] = OrganizationAddressGroupServiceGrpcAsyncIOTransport + _transport_registry["rest"] = OrganizationAddressGroupServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[OrganizationAddressGroupServiceTransport]: + """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 OrganizationAddressGroupServiceClient(metaclass=OrganizationAddressGroupServiceClientMeta): + """Organization AddressGroup is created under organization. + Requests against Organization AddressGroup will use project from + request credential for activation/quota/visibility check. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "networksecurity.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networksecurity.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + OrganizationAddressGroupServiceClient: 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: + OrganizationAddressGroupServiceClient: 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) -> OrganizationAddressGroupServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OrganizationAddressGroupServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def address_group_path(project: str,location: str,address_group: str,) -> str: + """Returns a fully-qualified address_group string.""" + return "projects/{project}/locations/{location}/addressGroups/{address_group}".format(project=project, location=location, address_group=address_group, ) + + @staticmethod + def parse_address_group_path(path: str) -> Dict[str,str]: + """Parses a address_group path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/addressGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, OrganizationAddressGroupServiceTransport, Callable[..., OrganizationAddressGroupServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the organization address group 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 (Optional[Union[str,OrganizationAddressGroupServiceTransport,Callable[..., OrganizationAddressGroupServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the OrganizationAddressGroupServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = OrganizationAddressGroupServiceClient._read_environment_variables() + self._client_cert_source = OrganizationAddressGroupServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = OrganizationAddressGroupServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, OrganizationAddressGroupServiceTransport) + if transport_provided: + # transport is a OrganizationAddressGroupServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(OrganizationAddressGroupServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + OrganizationAddressGroupServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[OrganizationAddressGroupServiceTransport], Callable[..., OrganizationAddressGroupServiceTransport]] = ( + OrganizationAddressGroupServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., OrganizationAddressGroupServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient`.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "credentialsType": None, + } + ) + + def list_address_groups(self, + request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupsPager: + r"""Lists address groups in a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_address_groups(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_address_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListAddressGroupsRequest, dict]): + The request object. Request used with the + ListAddressGroups method. + parent (str): + Required. The project and location from which the + AddressGroups should be listed, specified in the format + ``projects/*/locations/{location}``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsPager: + Response returned by the + ListAddressGroups method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.ListAddressGroupsRequest): + request = address_group.ListAddressGroupsRequest(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_address_groups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAddressGroupsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_address_group(self, + request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.AddressGroup: + r"""Gets details of a single address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_get_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetAddressGroupRequest( + name="name_value", + ) + + # Make the request + response = client.get_address_group(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.GetAddressGroupRequest, dict]): + The request object. Request used by the GetAddressGroup + method. + name (str): + Required. A name of the AddressGroup to get. Must be in + the format + ``projects/*/locations/{location}/addressGroups/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.types.AddressGroup: + AddressGroup is a resource that + specifies how a collection of IP/DNS + used in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.GetAddressGroupRequest): + request = address_group.GetAddressGroupRequest(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_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_address_group(self, + request: Optional[Union[gcn_address_group.CreateAddressGroupRequest, dict]] = None, + *, + parent: Optional[str] = None, + address_group: Optional[gcn_address_group.AddressGroup] = None, + address_group_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new address group in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_create_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.CreateAddressGroupRequest( + parent="parent_value", + address_group_id="address_group_id_value", + address_group=address_group, + ) + + # Make the request + operation = client.create_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CreateAddressGroupRequest, dict]): + The request object. Request used by the + CreateAddressGroup method. + parent (str): + Required. The parent resource of the AddressGroup. Must + be in the format ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + address_group (google.cloud.network_security_v1.types.AddressGroup): + Required. AddressGroup resource to be + created. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + address_group_id (str): + Required. Short name of the AddressGroup resource to be + created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "authz_policy". + + This corresponds to the ``address_group_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, address_group, address_group_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.CreateAddressGroupRequest): + request = gcn_address_group.CreateAddressGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if address_group is not None: + request.address_group = address_group + if address_group_id is not None: + request.address_group_id = address_group_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_address_group] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_address_group(self, + request: Optional[Union[gcn_address_group.UpdateAddressGroupRequest, dict]] = None, + *, + address_group: Optional[gcn_address_group.AddressGroup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates parameters of an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_update_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.UpdateAddressGroupRequest( + address_group=address_group, + ) + + # Make the request + operation = client.update_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.UpdateAddressGroupRequest, dict]): + The request object. Request used by the + UpdateAddressGroup method. + address_group (google.cloud.network_security_v1.types.AddressGroup): + Required. Updated AddressGroup + resource. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the AddressGroup resource by the update. + The fields specified in the update_mask are relative to + the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.UpdateAddressGroupRequest): + request = gcn_address_group.UpdateAddressGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group.name", request.address_group.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def add_address_group_items(self, + request: Optional[Union[gcn_address_group.AddAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Adds items to an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_add_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.AddAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.add_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.AddAddressGroupItemsRequest, dict]): + The request object. Request used by the + AddAddressGroupItems method. + address_group (str): + Required. A name of the AddressGroup to add items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + items (MutableSequence[str]): + Required. List of items to add. + This corresponds to the ``items`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, items] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.AddAddressGroupItemsRequest): + request = gcn_address_group.AddAddressGroupItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if items is not None: + request.items = items + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def remove_address_group_items(self, + request: Optional[Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Removes items from an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_remove_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.RemoveAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.remove_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest, dict]): + The request object. Request used by the + RemoveAddressGroupItems method. + address_group (str): + Required. A name of the AddressGroup to remove items + from. Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + items (MutableSequence[str]): + Required. List of items to remove. + This corresponds to the ``items`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, items] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.RemoveAddressGroupItemsRequest): + request = gcn_address_group.RemoveAddressGroupItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if items is not None: + request.items = items + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.remove_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def clone_address_group_items(self, + request: Optional[Union[gcn_address_group.CloneAddressGroupItemsRequest, dict]] = None, + *, + address_group: Optional[str] = None, + source_address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Clones items from one address group to another. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_clone_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.CloneAddressGroupItemsRequest( + address_group="address_group_value", + source_address_group="source_address_group_value", + ) + + # Make the request + operation = client.clone_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest, dict]): + The request object. Request used by the + CloneAddressGroupItems method. + address_group (str): + Required. A name of the AddressGroup to clone items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source_address_group (str): + Required. Source address group to + clone items from. + + This corresponds to the ``source_address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1.types.AddressGroup` AddressGroup is a resource that specifies how a collection of IP/DNS used + in Firewall Policy. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group, source_address_group] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.CloneAddressGroupItemsRequest): + request = gcn_address_group.CloneAddressGroupItemsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + if source_address_group is not None: + request.source_address_group = source_address_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.clone_address_group_items] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_address_group.AddressGroup, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_address_group(self, + request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_delete_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAddressGroupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.DeleteAddressGroupRequest, dict]): + The request object. Request used by the + DeleteAddressGroup method. + name (str): + Required. A name of the AddressGroup to delete. Must be + in the format + ``projects/*/locations/{location}/addressGroups/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, address_group.DeleteAddressGroupRequest): + request = address_group.DeleteAddressGroupRequest(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_address_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_address_group_references(self, + request: Optional[Union[gcn_address_group.ListAddressGroupReferencesRequest, dict]] = None, + *, + address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupReferencesPager: + r"""Lists references of an address group. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1 + + def sample_list_address_group_references(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupReferencesRequest( + address_group="address_group_value", + ) + + # Make the request + page_result = client.list_address_group_references(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest, dict]): + The request object. Request used by the + ListAddressGroupReferences method. + address_group (str): + Required. A name of the AddressGroup to clone items to. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + + This corresponds to the ``address_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesPager: + Response of the + ListAddressGroupReferences method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [address_group] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_address_group.ListAddressGroupReferencesRequest): + request = gcn_address_group.ListAddressGroupReferencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if address_group is not None: + request.address_group = address_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_address_group_references] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("address_group", request.address_group), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAddressGroupReferencesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "OrganizationAddressGroupServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "OrganizationAddressGroupServiceClient", +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/pagers.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/pagers.py new file mode 100644 index 000000000000..4c8ac9f092ff --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/pagers.py @@ -0,0 +1,306 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group + + +class ListAddressGroupsPager: + """A pager for iterating through ``list_address_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListAddressGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``address_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAddressGroups`` requests and continue to iterate + through the ``address_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListAddressGroupsResponse` + 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[..., address_group.ListAddressGroupsResponse], + request: address_group.ListAddressGroupsRequest, + response: address_group.ListAddressGroupsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListAddressGroupsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListAddressGroupsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = address_group.ListAddressGroupsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[address_group.ListAddressGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[address_group.AddressGroup]: + for page in self.pages: + yield from page.address_groups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAddressGroupsAsyncPager: + """A pager for iterating through ``list_address_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListAddressGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``address_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAddressGroups`` requests and continue to iterate + through the ``address_groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListAddressGroupsResponse` + 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[address_group.ListAddressGroupsResponse]], + request: address_group.ListAddressGroupsRequest, + response: address_group.ListAddressGroupsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListAddressGroupsRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListAddressGroupsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = address_group.ListAddressGroupsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[address_group.ListAddressGroupsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[address_group.AddressGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.address_groups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAddressGroupReferencesPager: + """A pager for iterating through ``list_address_group_references`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``address_group_references`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAddressGroupReferences`` requests and continue to iterate + through the ``address_group_references`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse` + 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[..., gcn_address_group.ListAddressGroupReferencesResponse], + request: gcn_address_group.ListAddressGroupReferencesRequest, + response: gcn_address_group.ListAddressGroupReferencesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = gcn_address_group.ListAddressGroupReferencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[gcn_address_group.ListAddressGroupReferencesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference]: + for page in self.pages: + yield from page.address_group_references + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAddressGroupReferencesAsyncPager: + """A pager for iterating through ``list_address_group_references`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``address_group_references`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAddressGroupReferences`` requests and continue to iterate + through the ``address_group_references`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse` + 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[gcn_address_group.ListAddressGroupReferencesResponse]], + request: gcn_address_group.ListAddressGroupReferencesRequest, + response: gcn_address_group.ListAddressGroupReferencesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest): + The initial request object. + response (google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = gcn_address_group.ListAddressGroupReferencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[gcn_address_group.ListAddressGroupReferencesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference]: + async def async_generator(): + async for page in self.pages: + for response in page.address_group_references: + 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/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/README.rst b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/README.rst new file mode 100644 index 000000000000..8daa4b8e0aeb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`OrganizationAddressGroupServiceTransport` is the ABC for all transports. +- public child `OrganizationAddressGroupServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `OrganizationAddressGroupServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseOrganizationAddressGroupServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `OrganizationAddressGroupServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py new file mode 100644 index 000000000000..a76ca8cbee11 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 OrganizationAddressGroupServiceTransport +from .grpc import OrganizationAddressGroupServiceGrpcTransport +from .grpc_asyncio import OrganizationAddressGroupServiceGrpcAsyncIOTransport +from .rest import OrganizationAddressGroupServiceRestTransport +from .rest import OrganizationAddressGroupServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OrganizationAddressGroupServiceTransport]] +_transport_registry['grpc'] = OrganizationAddressGroupServiceGrpcTransport +_transport_registry['grpc_asyncio'] = OrganizationAddressGroupServiceGrpcAsyncIOTransport +_transport_registry['rest'] = OrganizationAddressGroupServiceRestTransport + +__all__ = ( + 'OrganizationAddressGroupServiceTransport', + 'OrganizationAddressGroupServiceGrpcTransport', + 'OrganizationAddressGroupServiceGrpcAsyncIOTransport', + 'OrganizationAddressGroupServiceRestTransport', + 'OrganizationAddressGroupServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py new file mode 100644 index 000000000000..76cbe0a76417 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py @@ -0,0 +1,409 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.network_security_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class OrganizationAddressGroupServiceTransport(abc.ABC): + """Abstract transport class for OrganizationAddressGroupService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'networksecurity.googleapis.com' + + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_address_groups: gapic_v1.method.wrap_method( + self.list_address_groups, + default_timeout=None, + client_info=client_info, + ), + self.get_address_group: gapic_v1.method.wrap_method( + self.get_address_group, + default_timeout=None, + client_info=client_info, + ), + self.create_address_group: gapic_v1.method.wrap_method( + self.create_address_group, + default_timeout=None, + client_info=client_info, + ), + self.update_address_group: gapic_v1.method.wrap_method( + self.update_address_group, + default_timeout=None, + client_info=client_info, + ), + self.add_address_group_items: gapic_v1.method.wrap_method( + self.add_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.remove_address_group_items: gapic_v1.method.wrap_method( + self.remove_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.clone_address_group_items: gapic_v1.method.wrap_method( + self.clone_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.delete_address_group: gapic_v1.method.wrap_method( + self.delete_address_group, + default_timeout=None, + client_info=client_info, + ), + self.list_address_group_references: gapic_v1.method.wrap_method( + self.list_address_group_references, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_address_groups(self) -> Callable[ + [address_group.ListAddressGroupsRequest], + Union[ + address_group.ListAddressGroupsResponse, + Awaitable[address_group.ListAddressGroupsResponse] + ]]: + raise NotImplementedError() + + @property + def get_address_group(self) -> Callable[ + [address_group.GetAddressGroupRequest], + Union[ + address_group.AddressGroup, + Awaitable[address_group.AddressGroup] + ]]: + raise NotImplementedError() + + @property + def create_address_group(self) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_address_group(self) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def add_address_group_items(self) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def remove_address_group_items(self) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def clone_address_group_items(self) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_address_group(self) -> Callable[ + [address_group.DeleteAddressGroupRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_address_group_references(self) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + Union[ + gcn_address_group.ListAddressGroupReferencesResponse, + Awaitable[gcn_address_group.ListAddressGroupReferencesResponse] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'OrganizationAddressGroupServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py new file mode 100644 index 000000000000..ef0c38ea6214 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py @@ -0,0 +1,767 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import OrganizationAddressGroupServiceTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class OrganizationAddressGroupServiceGrpcTransport(OrganizationAddressGroupServiceTransport): + """gRPC backend transport for OrganizationAddressGroupService. + + Organization AddressGroup is created under organization. + Requests against Organization AddressGroup will use project from + request credential for activation/quota/visibility check. + + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_address_groups(self) -> Callable[ + [address_group.ListAddressGroupsRequest], + address_group.ListAddressGroupsResponse]: + r"""Return a callable for the list address groups method over gRPC. + + Lists address groups in a given project and location. + + Returns: + Callable[[~.ListAddressGroupsRequest], + ~.ListAddressGroupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_groups' not in self._stubs: + self._stubs['list_address_groups'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroups', + request_serializer=address_group.ListAddressGroupsRequest.serialize, + response_deserializer=address_group.ListAddressGroupsResponse.deserialize, + ) + return self._stubs['list_address_groups'] + + @property + def get_address_group(self) -> Callable[ + [address_group.GetAddressGroupRequest], + address_group.AddressGroup]: + r"""Return a callable for the get address group method over gRPC. + + Gets details of a single address group. + + Returns: + Callable[[~.GetAddressGroupRequest], + ~.AddressGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_group' not in self._stubs: + self._stubs['get_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/GetAddressGroup', + request_serializer=address_group.GetAddressGroupRequest.serialize, + response_deserializer=address_group.AddressGroup.deserialize, + ) + return self._stubs['get_address_group'] + + @property + def create_address_group(self) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + operations_pb2.Operation]: + r"""Return a callable for the create address group method over gRPC. + + Creates a new address group in a given project and + location. + + Returns: + Callable[[~.CreateAddressGroupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_address_group' not in self._stubs: + self._stubs['create_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CreateAddressGroup', + request_serializer=gcn_address_group.CreateAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_address_group'] + + @property + def update_address_group(self) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + operations_pb2.Operation]: + r"""Return a callable for the update address group method over gRPC. + + Updates parameters of an address group. + + Returns: + Callable[[~.UpdateAddressGroupRequest], + ~.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 'update_address_group' not in self._stubs: + self._stubs['update_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/UpdateAddressGroup', + request_serializer=gcn_address_group.UpdateAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_address_group'] + + @property + def add_address_group_items(self) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + operations_pb2.Operation]: + r"""Return a callable for the add address group items method over gRPC. + + Adds items to an address group. + + Returns: + Callable[[~.AddAddressGroupItemsRequest], + ~.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 'add_address_group_items' not in self._stubs: + self._stubs['add_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/AddAddressGroupItems', + request_serializer=gcn_address_group.AddAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_address_group_items'] + + @property + def remove_address_group_items(self) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + operations_pb2.Operation]: + r"""Return a callable for the remove address group items method over gRPC. + + Removes items from an address group. + + Returns: + Callable[[~.RemoveAddressGroupItemsRequest], + ~.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 'remove_address_group_items' not in self._stubs: + self._stubs['remove_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/RemoveAddressGroupItems', + request_serializer=gcn_address_group.RemoveAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_address_group_items'] + + @property + def clone_address_group_items(self) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + operations_pb2.Operation]: + r"""Return a callable for the clone address group items method over gRPC. + + Clones items from one address group to another. + + Returns: + Callable[[~.CloneAddressGroupItemsRequest], + ~.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 'clone_address_group_items' not in self._stubs: + self._stubs['clone_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CloneAddressGroupItems', + request_serializer=gcn_address_group.CloneAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['clone_address_group_items'] + + @property + def delete_address_group(self) -> Callable[ + [address_group.DeleteAddressGroupRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete address group method over gRPC. + + Deletes an address group. + + Returns: + Callable[[~.DeleteAddressGroupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_address_group' not in self._stubs: + self._stubs['delete_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/DeleteAddressGroup', + request_serializer=address_group.DeleteAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_address_group'] + + @property + def list_address_group_references(self) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + gcn_address_group.ListAddressGroupReferencesResponse]: + r"""Return a callable for the list address group references method over gRPC. + + Lists references of an address group. + + Returns: + Callable[[~.ListAddressGroupReferencesRequest], + ~.ListAddressGroupReferencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_group_references' not in self._stubs: + self._stubs['list_address_group_references'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroupReferences', + request_serializer=gcn_address_group.ListAddressGroupReferencesRequest.serialize, + response_deserializer=gcn_address_group.ListAddressGroupReferencesResponse.deserialize, + ) + return self._stubs['list_address_group_references'] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'OrganizationAddressGroupServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..4162831caf0e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py @@ -0,0 +1,873 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import OrganizationAddressGroupServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import OrganizationAddressGroupServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class OrganizationAddressGroupServiceGrpcAsyncIOTransport(OrganizationAddressGroupServiceTransport): + """gRPC AsyncIO backend transport for OrganizationAddressGroupService. + + Organization AddressGroup is created under organization. + Requests against Organization AddressGroup will use project from + request credential for activation/quota/visibility check. + + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_address_groups(self) -> Callable[ + [address_group.ListAddressGroupsRequest], + Awaitable[address_group.ListAddressGroupsResponse]]: + r"""Return a callable for the list address groups method over gRPC. + + Lists address groups in a given project and location. + + Returns: + Callable[[~.ListAddressGroupsRequest], + Awaitable[~.ListAddressGroupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_groups' not in self._stubs: + self._stubs['list_address_groups'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroups', + request_serializer=address_group.ListAddressGroupsRequest.serialize, + response_deserializer=address_group.ListAddressGroupsResponse.deserialize, + ) + return self._stubs['list_address_groups'] + + @property + def get_address_group(self) -> Callable[ + [address_group.GetAddressGroupRequest], + Awaitable[address_group.AddressGroup]]: + r"""Return a callable for the get address group method over gRPC. + + Gets details of a single address group. + + Returns: + Callable[[~.GetAddressGroupRequest], + Awaitable[~.AddressGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_group' not in self._stubs: + self._stubs['get_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/GetAddressGroup', + request_serializer=address_group.GetAddressGroupRequest.serialize, + response_deserializer=address_group.AddressGroup.deserialize, + ) + return self._stubs['get_address_group'] + + @property + def create_address_group(self) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create address group method over gRPC. + + Creates a new address group in a given project and + location. + + Returns: + Callable[[~.CreateAddressGroupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_address_group' not in self._stubs: + self._stubs['create_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CreateAddressGroup', + request_serializer=gcn_address_group.CreateAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_address_group'] + + @property + def update_address_group(self) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update address group method over gRPC. + + Updates parameters of an address group. + + Returns: + Callable[[~.UpdateAddressGroupRequest], + 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 'update_address_group' not in self._stubs: + self._stubs['update_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/UpdateAddressGroup', + request_serializer=gcn_address_group.UpdateAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_address_group'] + + @property + def add_address_group_items(self) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the add address group items method over gRPC. + + Adds items to an address group. + + Returns: + Callable[[~.AddAddressGroupItemsRequest], + 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 'add_address_group_items' not in self._stubs: + self._stubs['add_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/AddAddressGroupItems', + request_serializer=gcn_address_group.AddAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['add_address_group_items'] + + @property + def remove_address_group_items(self) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the remove address group items method over gRPC. + + Removes items from an address group. + + Returns: + Callable[[~.RemoveAddressGroupItemsRequest], + 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 'remove_address_group_items' not in self._stubs: + self._stubs['remove_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/RemoveAddressGroupItems', + request_serializer=gcn_address_group.RemoveAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['remove_address_group_items'] + + @property + def clone_address_group_items(self) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the clone address group items method over gRPC. + + Clones items from one address group to another. + + Returns: + Callable[[~.CloneAddressGroupItemsRequest], + 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 'clone_address_group_items' not in self._stubs: + self._stubs['clone_address_group_items'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CloneAddressGroupItems', + request_serializer=gcn_address_group.CloneAddressGroupItemsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['clone_address_group_items'] + + @property + def delete_address_group(self) -> Callable[ + [address_group.DeleteAddressGroupRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete address group method over gRPC. + + Deletes an address group. + + Returns: + Callable[[~.DeleteAddressGroupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_address_group' not in self._stubs: + self._stubs['delete_address_group'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/DeleteAddressGroup', + request_serializer=address_group.DeleteAddressGroupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_address_group'] + + @property + def list_address_group_references(self) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + Awaitable[gcn_address_group.ListAddressGroupReferencesResponse]]: + r"""Return a callable for the list address group references method over gRPC. + + Lists references of an address group. + + Returns: + Callable[[~.ListAddressGroupReferencesRequest], + Awaitable[~.ListAddressGroupReferencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_address_group_references' not in self._stubs: + self._stubs['list_address_group_references'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroupReferences', + request_serializer=gcn_address_group.ListAddressGroupReferencesRequest.serialize, + response_deserializer=gcn_address_group.ListAddressGroupReferencesResponse.deserialize, + ) + return self._stubs['list_address_group_references'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_address_groups: self._wrap_method( + self.list_address_groups, + default_timeout=None, + client_info=client_info, + ), + self.get_address_group: self._wrap_method( + self.get_address_group, + default_timeout=None, + client_info=client_info, + ), + self.create_address_group: self._wrap_method( + self.create_address_group, + default_timeout=None, + client_info=client_info, + ), + self.update_address_group: self._wrap_method( + self.update_address_group, + default_timeout=None, + client_info=client_info, + ), + self.add_address_group_items: self._wrap_method( + self.add_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.remove_address_group_items: self._wrap_method( + self.remove_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.clone_address_group_items: self._wrap_method( + self.clone_address_group_items, + default_timeout=None, + client_info=client_info, + ), + self.delete_address_group: self._wrap_method( + self.delete_address_group, + default_timeout=None, + client_info=client_info, + ), + self.list_address_group_references: self._wrap_method( + self.list_address_group_references, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'OrganizationAddressGroupServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py new file mode 100644 index 000000000000..2dc3bcb3a05e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py @@ -0,0 +1,3042 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 +import google.protobuf + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseOrganizationAddressGroupServiceRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class OrganizationAddressGroupServiceRestInterceptor: + """Interceptor for OrganizationAddressGroupService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the OrganizationAddressGroupServiceRestTransport. + + .. code-block:: python + class MyCustomOrganizationAddressGroupServiceInterceptor(OrganizationAddressGroupServiceRestInterceptor): + def pre_add_address_group_items(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_address_group_items(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_clone_address_group_items(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_clone_address_group_items(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_address_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_address_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_address_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_address_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_address_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_address_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_address_group_references(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_address_group_references(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_address_groups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_address_groups(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_remove_address_group_items(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_remove_address_group_items(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_address_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_address_group(self, response): + logging.log(f"Received response: {response}") + return response + + transport = OrganizationAddressGroupServiceRestTransport(interceptor=MyCustomOrganizationAddressGroupServiceInterceptor()) + client = OrganizationAddressGroupServiceClient(transport=transport) + + + """ + def pre_add_address_group_items(self, request: gcn_address_group.AddAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.AddAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for add_address_group_items + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_add_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for add_address_group_items + + DEPRECATED. Please use the `post_add_address_group_items_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. This `post_add_address_group_items` interceptor runs + before the `post_add_address_group_items_with_metadata` interceptor. + """ + return response + + def post_add_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for add_address_group_items + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationAddressGroupService server but before it is returned to user code. + + We recommend only using this `post_add_address_group_items_with_metadata` + interceptor in new development instead of the `post_add_address_group_items` interceptor. + When both interceptors are used, this `post_add_address_group_items_with_metadata` interceptor runs after the + `post_add_address_group_items` interceptor. The (possibly modified) response returned by + `post_add_address_group_items` will be passed to + `post_add_address_group_items_with_metadata`. + """ + return response, metadata + + def pre_clone_address_group_items(self, request: gcn_address_group.CloneAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.CloneAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for clone_address_group_items + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_clone_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for clone_address_group_items + + DEPRECATED. Please use the `post_clone_address_group_items_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. This `post_clone_address_group_items` interceptor runs + before the `post_clone_address_group_items_with_metadata` interceptor. + """ + return response + + def post_clone_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for clone_address_group_items + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationAddressGroupService server but before it is returned to user code. + + We recommend only using this `post_clone_address_group_items_with_metadata` + interceptor in new development instead of the `post_clone_address_group_items` interceptor. + When both interceptors are used, this `post_clone_address_group_items_with_metadata` interceptor runs after the + `post_clone_address_group_items` interceptor. The (possibly modified) response returned by + `post_clone_address_group_items` will be passed to + `post_clone_address_group_items_with_metadata`. + """ + return response, metadata + + def pre_create_address_group(self, request: gcn_address_group.CreateAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.CreateAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_address_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_create_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_address_group + + DEPRECATED. Please use the `post_create_address_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. This `post_create_address_group` interceptor runs + before the `post_create_address_group_with_metadata` interceptor. + """ + return response + + def post_create_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_address_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationAddressGroupService server but before it is returned to user code. + + We recommend only using this `post_create_address_group_with_metadata` + interceptor in new development instead of the `post_create_address_group` interceptor. + When both interceptors are used, this `post_create_address_group_with_metadata` interceptor runs after the + `post_create_address_group` interceptor. The (possibly modified) response returned by + `post_create_address_group` will be passed to + `post_create_address_group_with_metadata`. + """ + return response, metadata + + def pre_delete_address_group(self, request: address_group.DeleteAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.DeleteAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_address_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_delete_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_address_group + + DEPRECATED. Please use the `post_delete_address_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. This `post_delete_address_group` interceptor runs + before the `post_delete_address_group_with_metadata` interceptor. + """ + return response + + def post_delete_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_address_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationAddressGroupService server but before it is returned to user code. + + We recommend only using this `post_delete_address_group_with_metadata` + interceptor in new development instead of the `post_delete_address_group` interceptor. + When both interceptors are used, this `post_delete_address_group_with_metadata` interceptor runs after the + `post_delete_address_group` interceptor. The (possibly modified) response returned by + `post_delete_address_group` will be passed to + `post_delete_address_group_with_metadata`. + """ + return response, metadata + + def pre_get_address_group(self, request: address_group.GetAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.GetAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_address_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_get_address_group(self, response: address_group.AddressGroup) -> address_group.AddressGroup: + """Post-rpc interceptor for get_address_group + + DEPRECATED. Please use the `post_get_address_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. This `post_get_address_group` interceptor runs + before the `post_get_address_group_with_metadata` interceptor. + """ + return response + + def post_get_address_group_with_metadata(self, response: address_group.AddressGroup, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.AddressGroup, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_address_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationAddressGroupService server but before it is returned to user code. + + We recommend only using this `post_get_address_group_with_metadata` + interceptor in new development instead of the `post_get_address_group` interceptor. + When both interceptors are used, this `post_get_address_group_with_metadata` interceptor runs after the + `post_get_address_group` interceptor. The (possibly modified) response returned by + `post_get_address_group` will be passed to + `post_get_address_group_with_metadata`. + """ + return response, metadata + + def pre_list_address_group_references(self, request: gcn_address_group.ListAddressGroupReferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.ListAddressGroupReferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_address_group_references + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_list_address_group_references(self, response: gcn_address_group.ListAddressGroupReferencesResponse) -> gcn_address_group.ListAddressGroupReferencesResponse: + """Post-rpc interceptor for list_address_group_references + + DEPRECATED. Please use the `post_list_address_group_references_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. This `post_list_address_group_references` interceptor runs + before the `post_list_address_group_references_with_metadata` interceptor. + """ + return response + + def post_list_address_group_references_with_metadata(self, response: gcn_address_group.ListAddressGroupReferencesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.ListAddressGroupReferencesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_address_group_references + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationAddressGroupService server but before it is returned to user code. + + We recommend only using this `post_list_address_group_references_with_metadata` + interceptor in new development instead of the `post_list_address_group_references` interceptor. + When both interceptors are used, this `post_list_address_group_references_with_metadata` interceptor runs after the + `post_list_address_group_references` interceptor. The (possibly modified) response returned by + `post_list_address_group_references` will be passed to + `post_list_address_group_references_with_metadata`. + """ + return response, metadata + + def pre_list_address_groups(self, request: address_group.ListAddressGroupsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.ListAddressGroupsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_address_groups + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_list_address_groups(self, response: address_group.ListAddressGroupsResponse) -> address_group.ListAddressGroupsResponse: + """Post-rpc interceptor for list_address_groups + + DEPRECATED. Please use the `post_list_address_groups_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. This `post_list_address_groups` interceptor runs + before the `post_list_address_groups_with_metadata` interceptor. + """ + return response + + def post_list_address_groups_with_metadata(self, response: address_group.ListAddressGroupsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.ListAddressGroupsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_address_groups + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationAddressGroupService server but before it is returned to user code. + + We recommend only using this `post_list_address_groups_with_metadata` + interceptor in new development instead of the `post_list_address_groups` interceptor. + When both interceptors are used, this `post_list_address_groups_with_metadata` interceptor runs after the + `post_list_address_groups` interceptor. The (possibly modified) response returned by + `post_list_address_groups` will be passed to + `post_list_address_groups_with_metadata`. + """ + return response, metadata + + def pre_remove_address_group_items(self, request: gcn_address_group.RemoveAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.RemoveAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for remove_address_group_items + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_remove_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for remove_address_group_items + + DEPRECATED. Please use the `post_remove_address_group_items_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. This `post_remove_address_group_items` interceptor runs + before the `post_remove_address_group_items_with_metadata` interceptor. + """ + return response + + def post_remove_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for remove_address_group_items + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationAddressGroupService server but before it is returned to user code. + + We recommend only using this `post_remove_address_group_items_with_metadata` + interceptor in new development instead of the `post_remove_address_group_items` interceptor. + When both interceptors are used, this `post_remove_address_group_items_with_metadata` interceptor runs after the + `post_remove_address_group_items` interceptor. The (possibly modified) response returned by + `post_remove_address_group_items` will be passed to + `post_remove_address_group_items_with_metadata`. + """ + return response, metadata + + def pre_update_address_group(self, request: gcn_address_group.UpdateAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.UpdateAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_address_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_update_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_address_group + + DEPRECATED. Please use the `post_update_address_group_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. This `post_update_address_group` interceptor runs + before the `post_update_address_group_with_metadata` interceptor. + """ + return response + + def post_update_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_address_group + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationAddressGroupService server but before it is returned to user code. + + We recommend only using this `post_update_address_group_with_metadata` + interceptor in new development instead of the `post_update_address_group` interceptor. + When both interceptors are used, this `post_update_address_group_with_metadata` interceptor runs after the + `post_update_address_group` interceptor. The (possibly modified) response returned by + `post_update_address_group` will be passed to + `post_update_address_group_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationAddressGroupService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the OrganizationAddressGroupService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class OrganizationAddressGroupServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: OrganizationAddressGroupServiceRestInterceptor + + +class OrganizationAddressGroupServiceRestTransport(_BaseOrganizationAddressGroupServiceRestTransport): + """REST backend synchronous transport for OrganizationAddressGroupService. + + Organization AddressGroup is created under organization. + Requests against Organization AddressGroup will use project from + request credential for activation/quota/visibility check. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[OrganizationAddressGroupServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or OrganizationAddressGroupServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _AddAddressGroupItems(_BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.AddAddressGroupItems") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_address_group.AddAddressGroupItemsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the add address group items method over HTTP. + + Args: + request (~.gcn_address_group.AddAddressGroupItemsRequest): + The request object. Request used by the + AddAddressGroupItems method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_http_options() + + request, metadata = self._interceptor.pre_add_address_group_items(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_transcoded_request(http_options, request) + + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.AddAddressGroupItems", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "AddAddressGroupItems", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._AddAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_add_address_group_items(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_add_address_group_items_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.add_address_group_items", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "AddAddressGroupItems", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CloneAddressGroupItems(_BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.CloneAddressGroupItems") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_address_group.CloneAddressGroupItemsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the clone address group items method over HTTP. + + Args: + request (~.gcn_address_group.CloneAddressGroupItemsRequest): + The request object. Request used by the + CloneAddressGroupItems method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_http_options() + + request, metadata = self._interceptor.pre_clone_address_group_items(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_transcoded_request(http_options, request) + + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.CloneAddressGroupItems", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "CloneAddressGroupItems", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._CloneAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_clone_address_group_items(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_clone_address_group_items_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.clone_address_group_items", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "CloneAddressGroupItems", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAddressGroup(_BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.CreateAddressGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_address_group.CreateAddressGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create address group method over HTTP. + + Args: + request (~.gcn_address_group.CreateAddressGroupRequest): + The request object. Request used by the + CreateAddressGroup method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_http_options() + + request, metadata = self._interceptor.pre_create_address_group(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_transcoded_request(http_options, request) + + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.CreateAddressGroup", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "CreateAddressGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._CreateAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_address_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_address_group_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.create_address_group", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "CreateAddressGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAddressGroup(_BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.DeleteAddressGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: address_group.DeleteAddressGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete address group method over HTTP. + + Args: + request (~.address_group.DeleteAddressGroupRequest): + The request object. Request used by the + DeleteAddressGroup method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_http_options() + + request, metadata = self._interceptor.pre_delete_address_group(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.DeleteAddressGroup", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "DeleteAddressGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._DeleteAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_address_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_address_group_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.delete_address_group", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "DeleteAddressGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAddressGroup(_BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.GetAddressGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: address_group.GetAddressGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> address_group.AddressGroup: + r"""Call the get address group method over HTTP. + + Args: + request (~.address_group.GetAddressGroupRequest): + The request object. Request used by the GetAddressGroup + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.address_group.AddressGroup: + AddressGroup is a resource that + specifies how a collection of IP/DNS + used in Firewall Policy. + + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_http_options() + + request, metadata = self._interceptor.pre_get_address_group(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.GetAddressGroup", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "GetAddressGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._GetAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = address_group.AddressGroup() + pb_resp = address_group.AddressGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_address_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_address_group_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = address_group.AddressGroup.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.get_address_group", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "GetAddressGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAddressGroupReferences(_BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.ListAddressGroupReferences") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: gcn_address_group.ListAddressGroupReferencesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gcn_address_group.ListAddressGroupReferencesResponse: + r"""Call the list address group + references method over HTTP. + + Args: + request (~.gcn_address_group.ListAddressGroupReferencesRequest): + The request object. Request used by the + ListAddressGroupReferences method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcn_address_group.ListAddressGroupReferencesResponse: + Response of the + ListAddressGroupReferences method. + + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_http_options() + + request, metadata = self._interceptor.pre_list_address_group_references(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.ListAddressGroupReferences", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "ListAddressGroupReferences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._ListAddressGroupReferences._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcn_address_group.ListAddressGroupReferencesResponse() + pb_resp = gcn_address_group.ListAddressGroupReferencesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_address_group_references(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_address_group_references_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gcn_address_group.ListAddressGroupReferencesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.list_address_group_references", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "ListAddressGroupReferences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAddressGroups(_BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.ListAddressGroups") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: address_group.ListAddressGroupsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> address_group.ListAddressGroupsResponse: + r"""Call the list address groups method over HTTP. + + Args: + request (~.address_group.ListAddressGroupsRequest): + The request object. Request used with the + ListAddressGroups method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.address_group.ListAddressGroupsResponse: + Response returned by the + ListAddressGroups method. + + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_http_options() + + request, metadata = self._interceptor.pre_list_address_groups(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.ListAddressGroups", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "ListAddressGroups", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._ListAddressGroups._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = address_group.ListAddressGroupsResponse() + pb_resp = address_group.ListAddressGroupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_address_groups(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_address_groups_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = address_group.ListAddressGroupsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.list_address_groups", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "ListAddressGroups", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RemoveAddressGroupItems(_BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.RemoveAddressGroupItems") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_address_group.RemoveAddressGroupItemsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the remove address group + items method over HTTP. + + Args: + request (~.gcn_address_group.RemoveAddressGroupItemsRequest): + The request object. Request used by the + RemoveAddressGroupItems method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_http_options() + + request, metadata = self._interceptor.pre_remove_address_group_items(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_transcoded_request(http_options, request) + + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.RemoveAddressGroupItems", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "RemoveAddressGroupItems", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._RemoveAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_remove_address_group_items(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_remove_address_group_items_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.remove_address_group_items", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "RemoveAddressGroupItems", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAddressGroup(_BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.UpdateAddressGroup") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_address_group.UpdateAddressGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update address group method over HTTP. + + Args: + request (~.gcn_address_group.UpdateAddressGroupRequest): + The request object. Request used by the + UpdateAddressGroup method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_http_options() + + request, metadata = self._interceptor.pre_update_address_group(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_transcoded_request(http_options, request) + + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.UpdateAddressGroup", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "UpdateAddressGroup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._UpdateAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_address_group(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_address_group_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.update_address_group", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "UpdateAddressGroup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def add_address_group_items(self) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AddAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + + @property + def clone_address_group_items(self) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CloneAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_address_group(self) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAddressGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_address_group(self) -> Callable[ + [address_group.DeleteAddressGroupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAddressGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_address_group(self) -> Callable[ + [address_group.GetAddressGroupRequest], + address_group.AddressGroup]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAddressGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_address_group_references(self) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + gcn_address_group.ListAddressGroupReferencesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAddressGroupReferences(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_address_groups(self) -> Callable[ + [address_group.ListAddressGroupsRequest], + address_group.ListAddressGroupsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAddressGroups(self._session, self._host, self._interceptor) # type: ignore + + @property + def remove_address_group_items(self) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RemoveAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_address_group(self) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAddressGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation._get_http_options() + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.GetLocation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.GetLocation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations._get_http_options() + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.ListLocations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.ListLocations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.GetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.GetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.SetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.SetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.TestIamPermissions", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.TestIamPermissions", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.CancelOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.GetOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations, OrganizationAddressGroupServiceRestStub): + def __hash__(self): + return hash("OrganizationAddressGroupServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.ListOperations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationAddressGroupServiceRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'OrganizationAddressGroupServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py new file mode 100644 index 000000000000..8aa0195a0747 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py @@ -0,0 +1,800 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import OrganizationAddressGroupServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseOrganizationAddressGroupServiceRestTransport(OrganizationAddressGroupServiceTransport): + """Base REST backend transport for OrganizationAddressGroupService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[Any]): 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. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseAddAddressGroupItems: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{address_group=organizations/*/locations/*/addressGroups/*}:addItems', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.AddAddressGroupItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCloneAddressGroupItems: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{address_group=organizations/*/locations/*/addressGroups/*}:cloneItems', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.CloneAddressGroupItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateAddressGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "addressGroupId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=organizations/*/locations/*}/addressGroups', + 'body': 'address_group', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.CreateAddressGroupRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteAddressGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/locations/*/addressGroups/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = address_group.DeleteAddressGroupRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAddressGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*/addressGroups/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = address_group.GetAddressGroupRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAddressGroupReferences: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{address_group=organizations/*/locations/*/addressGroups/*}:listReferences', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.ListAddressGroupReferencesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAddressGroups: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=organizations/*/locations/*}/addressGroups', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = address_group.ListAddressGroupsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRemoveAddressGroupItems: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{address_group=organizations/*/locations/*/addressGroups/*}:removeItems', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.RemoveAddressGroupItemsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAddressGroup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{address_group.name=organizations/*/locations/*/addressGroups/*}', + 'body': 'address_group', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_address_group.UpdateAddressGroupRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'delete', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=organizations/*/locations/*}/operations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseOrganizationAddressGroupServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/__init__.py new file mode 100644 index 000000000000..9198dadc54e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/__init__.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .address_group import ( + AddAddressGroupItemsRequest, + AddressGroup, + CloneAddressGroupItemsRequest, + CreateAddressGroupRequest, + DeleteAddressGroupRequest, + GetAddressGroupRequest, + ListAddressGroupReferencesRequest, + ListAddressGroupReferencesResponse, + ListAddressGroupsRequest, + ListAddressGroupsResponse, + RemoveAddressGroupItemsRequest, + UpdateAddressGroupRequest, +) +from .authorization_policy import ( + AuthorizationPolicy, + CreateAuthorizationPolicyRequest, + DeleteAuthorizationPolicyRequest, + GetAuthorizationPolicyRequest, + ListAuthorizationPoliciesRequest, + ListAuthorizationPoliciesResponse, + UpdateAuthorizationPolicyRequest, +) +from .client_tls_policy import ( + ClientTlsPolicy, + CreateClientTlsPolicyRequest, + DeleteClientTlsPolicyRequest, + GetClientTlsPolicyRequest, + ListClientTlsPoliciesRequest, + ListClientTlsPoliciesResponse, + UpdateClientTlsPolicyRequest, +) +from .common import ( + OperationMetadata, +) +from .server_tls_policy import ( + CreateServerTlsPolicyRequest, + DeleteServerTlsPolicyRequest, + GetServerTlsPolicyRequest, + ListServerTlsPoliciesRequest, + ListServerTlsPoliciesResponse, + ServerTlsPolicy, + UpdateServerTlsPolicyRequest, +) +from .tls import ( + CertificateProvider, + CertificateProviderInstance, + GrpcEndpoint, + ValidationCA, +) + +__all__ = ( + 'AddAddressGroupItemsRequest', + 'AddressGroup', + 'CloneAddressGroupItemsRequest', + 'CreateAddressGroupRequest', + 'DeleteAddressGroupRequest', + 'GetAddressGroupRequest', + 'ListAddressGroupReferencesRequest', + 'ListAddressGroupReferencesResponse', + 'ListAddressGroupsRequest', + 'ListAddressGroupsResponse', + 'RemoveAddressGroupItemsRequest', + 'UpdateAddressGroupRequest', + 'AuthorizationPolicy', + 'CreateAuthorizationPolicyRequest', + 'DeleteAuthorizationPolicyRequest', + 'GetAuthorizationPolicyRequest', + 'ListAuthorizationPoliciesRequest', + 'ListAuthorizationPoliciesResponse', + 'UpdateAuthorizationPolicyRequest', + 'ClientTlsPolicy', + 'CreateClientTlsPolicyRequest', + 'DeleteClientTlsPolicyRequest', + 'GetClientTlsPolicyRequest', + 'ListClientTlsPoliciesRequest', + 'ListClientTlsPoliciesResponse', + 'UpdateClientTlsPolicyRequest', + 'OperationMetadata', + 'CreateServerTlsPolicyRequest', + 'DeleteServerTlsPolicyRequest', + 'GetServerTlsPolicyRequest', + 'ListServerTlsPoliciesRequest', + 'ListServerTlsPoliciesResponse', + 'ServerTlsPolicy', + 'UpdateServerTlsPolicyRequest', + 'CertificateProvider', + 'CertificateProviderInstance', + 'GrpcEndpoint', + 'ValidationCA', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/address_group.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/address_group.py new file mode 100644 index 000000000000..b3f727df5c06 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/address_group.py @@ -0,0 +1,625 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1', + manifest={ + 'AddressGroup', + 'ListAddressGroupsRequest', + 'ListAddressGroupsResponse', + 'GetAddressGroupRequest', + 'CreateAddressGroupRequest', + 'UpdateAddressGroupRequest', + 'DeleteAddressGroupRequest', + 'AddAddressGroupItemsRequest', + 'RemoveAddressGroupItemsRequest', + 'CloneAddressGroupItemsRequest', + 'ListAddressGroupReferencesRequest', + 'ListAddressGroupReferencesResponse', + }, +) + + +class AddressGroup(proto.Message): + r"""AddressGroup is a resource that specifies how a collection of + IP/DNS used in Firewall Policy. + + Attributes: + name (str): + Required. Name of the AddressGroup resource. It matches + pattern + ``projects/*/locations/{location}/addressGroups/``. + description (str): + Optional. Free-text description of the + resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + labels (MutableMapping[str, str]): + Optional. Set of label tags associated with + the AddressGroup resource. + type_ (google.cloud.network_security_v1.types.AddressGroup.Type): + Required. The type of the Address Group. + Possible values are "IPv4" or "IPV6". + items (MutableSequence[str]): + Optional. List of items. + capacity (int): + Required. Capacity of the Address Group + self_link (str): + Output only. Server-defined fully-qualified + URL for this resource. + purpose (MutableSequence[google.cloud.network_security_v1.types.AddressGroup.Purpose]): + Optional. List of supported purposes of the + Address Group. + """ + class Type(proto.Enum): + r"""Possible type of the Address Group. + + Values: + TYPE_UNSPECIFIED (0): + Default value. + IPV4 (1): + IP v4 ranges. + IPV6 (2): + IP v6 ranges. + """ + TYPE_UNSPECIFIED = 0 + IPV4 = 1 + IPV6 = 2 + + class Purpose(proto.Enum): + r"""Purpose of the Address Group. + + Values: + PURPOSE_UNSPECIFIED (0): + Default value. Should never happen. + DEFAULT (1): + Address Group is distributed to VMC, and is + usable in Firewall Policies and other systems + that rely on VMC. + CLOUD_ARMOR (2): + Address Group is usable in Cloud Armor. + """ + PURPOSE_UNSPECIFIED = 0 + DEFAULT = 1 + CLOUD_ARMOR = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + type_: Type = proto.Field( + proto.ENUM, + number=6, + enum=Type, + ) + items: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + capacity: int = proto.Field( + proto.INT32, + number=8, + ) + self_link: str = proto.Field( + proto.STRING, + number=9, + ) + purpose: MutableSequence[Purpose] = proto.RepeatedField( + proto.ENUM, + number=10, + enum=Purpose, + ) + + +class ListAddressGroupsRequest(proto.Message): + r"""Request used with the ListAddressGroups method. + + Attributes: + parent (str): + Required. The project and location from which the + AddressGroups should be listed, specified in the format + ``projects/*/locations/{location}``. + page_size (int): + Maximum number of AddressGroups to return per + call. + page_token (str): + The value returned by the last ``ListAddressGroupsResponse`` + Indicates that this is a continuation of a prior + ``ListAddressGroups`` call, and that the system should + return the next page of data. + return_partial_success (bool): + Optional. If true, allow partial responses + for multi-regional Aggregated List requests. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListAddressGroupsResponse(proto.Message): + r"""Response returned by the ListAddressGroups method. + + Attributes: + address_groups (MutableSequence[google.cloud.network_security_v1.types.AddressGroup]): + List of AddressGroups resources. + next_page_token (str): + If there might be 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``. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + address_groups: MutableSequence['AddressGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AddressGroup', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetAddressGroupRequest(proto.Message): + r"""Request used by the GetAddressGroup method. + + Attributes: + name (str): + Required. A name of the AddressGroup to get. Must be in the + format ``projects/*/locations/{location}/addressGroups/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAddressGroupRequest(proto.Message): + r"""Request used by the CreateAddressGroup method. + + Attributes: + parent (str): + Required. The parent resource of the AddressGroup. Must be + in the format ``projects/*/locations/{location}``. + address_group_id (str): + Required. Short name of the AddressGroup resource to be + created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and underscores, + and should not start with a number. E.g. "authz_policy". + address_group (google.cloud.network_security_v1.types.AddressGroup): + Required. AddressGroup resource to be + created. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + address_group_id: str = proto.Field( + proto.STRING, + number=2, + ) + address_group: 'AddressGroup' = proto.Field( + proto.MESSAGE, + number=3, + message='AddressGroup', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateAddressGroupRequest(proto.Message): + r"""Request used by the UpdateAddressGroup method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the AddressGroup resource by the update. The + fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + address_group (google.cloud.network_security_v1.types.AddressGroup): + Required. Updated AddressGroup resource. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + address_group: 'AddressGroup' = proto.Field( + proto.MESSAGE, + number=2, + message='AddressGroup', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteAddressGroupRequest(proto.Message): + r"""Request used by the DeleteAddressGroup method. + + Attributes: + name (str): + Required. A name of the AddressGroup to delete. Must be in + the format + ``projects/*/locations/{location}/addressGroups/*``. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AddAddressGroupItemsRequest(proto.Message): + r"""Request used by the AddAddressGroupItems method. + + Attributes: + address_group (str): + Required. A name of the AddressGroup to add items to. Must + be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + items (MutableSequence[str]): + Required. List of items to add. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + address_group: str = proto.Field( + proto.STRING, + number=1, + ) + items: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class RemoveAddressGroupItemsRequest(proto.Message): + r"""Request used by the RemoveAddressGroupItems method. + + Attributes: + address_group (str): + Required. A name of the AddressGroup to remove items from. + Must be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + items (MutableSequence[str]): + Required. List of items to remove. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + address_group: str = proto.Field( + proto.STRING, + number=1, + ) + items: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CloneAddressGroupItemsRequest(proto.Message): + r"""Request used by the CloneAddressGroupItems method. + + Attributes: + address_group (str): + Required. A name of the AddressGroup to clone items to. Must + be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + source_address_group (str): + Required. Source address group to clone items + from. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + address_group: str = proto.Field( + proto.STRING, + number=1, + ) + source_address_group: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAddressGroupReferencesRequest(proto.Message): + r"""Request used by the ListAddressGroupReferences method. + + Attributes: + address_group (str): + Required. A name of the AddressGroup to clone items to. Must + be in the format + ``projects|organization/*/locations/{location}/addressGroups/*``. + page_size (int): + The maximum number of references to return. If unspecified, + server will pick an appropriate default. Server may return + fewer items than requested. A caller should only rely on + response's + [next_page_token][google.cloud.networksecurity.v1.ListAddressGroupReferencesResponse.next_page_token] + to determine if there are more AddressGroupUsers left to be + queried. + page_token (str): + The next_page_token value returned from a previous List + request, if any. + """ + + address_group: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAddressGroupReferencesResponse(proto.Message): + r"""Response of the ListAddressGroupReferences method. + + Attributes: + address_group_references (MutableSequence[google.cloud.network_security_v1.types.ListAddressGroupReferencesResponse.AddressGroupReference]): + A list of references that matches the + specified filter in the request. + next_page_token (str): + If there might be 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``. + """ + + class AddressGroupReference(proto.Message): + r"""The Reference of AddressGroup. + + Attributes: + firewall_policy (str): + FirewallPolicy that is using the Address + Group. + security_policy (str): + Cloud Armor SecurityPolicy that is using the + Address Group. + rule_priority (int): + Rule priority of the FirewallPolicy that is + using the Address Group. + """ + + firewall_policy: str = proto.Field( + proto.STRING, + number=1, + ) + security_policy: str = proto.Field( + proto.STRING, + number=4, + ) + rule_priority: int = proto.Field( + proto.INT32, + number=2, + ) + + @property + def raw_page(self): + return self + + address_group_references: MutableSequence[AddressGroupReference] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AddressGroupReference, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/authorization_policy.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/authorization_policy.py new file mode 100644 index 000000000000..7623a1508e63 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/authorization_policy.py @@ -0,0 +1,425 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1', + manifest={ + 'AuthorizationPolicy', + 'ListAuthorizationPoliciesRequest', + 'ListAuthorizationPoliciesResponse', + 'GetAuthorizationPolicyRequest', + 'CreateAuthorizationPolicyRequest', + 'UpdateAuthorizationPolicyRequest', + 'DeleteAuthorizationPolicyRequest', + }, +) + + +class AuthorizationPolicy(proto.Message): + r"""AuthorizationPolicy is a resource that specifies how a server + should authorize incoming connections. This resource in itself + does not change the configuration unless it's attached to a + target https proxy or endpoint config selector resource. + + Attributes: + name (str): + Required. Name of the AuthorizationPolicy resource. It + matches pattern + ``projects/{project}/locations/{location}/authorizationPolicies/``. + description (str): + Optional. Free-text description of the + resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + labels (MutableMapping[str, str]): + Optional. Set of label tags associated with + the AuthorizationPolicy resource. + action (google.cloud.network_security_v1.types.AuthorizationPolicy.Action): + Required. The action to take when a rule + match is found. Possible values are "ALLOW" or + "DENY". + rules (MutableSequence[google.cloud.network_security_v1.types.AuthorizationPolicy.Rule]): + Optional. List of rules to match. Note that at least one of + the rules must match in order for the action specified in + the 'action' field to be taken. A rule is a match if there + is a matching source and destination. If left blank, the + action specified in the ``action`` field will be applied on + every request. + """ + class Action(proto.Enum): + r"""Possible values that define what action to take. + + Values: + ACTION_UNSPECIFIED (0): + Default value. + ALLOW (1): + Grant access. + DENY (2): + Deny access. + Deny rules should be avoided unless they are + used to provide a default "deny all" fallback. + """ + ACTION_UNSPECIFIED = 0 + ALLOW = 1 + DENY = 2 + + class Rule(proto.Message): + r"""Specification of rules. + + Attributes: + sources (MutableSequence[google.cloud.network_security_v1.types.AuthorizationPolicy.Rule.Source]): + Optional. List of attributes for the traffic source. All of + the sources must match. A source is a match if both + principals and ip_blocks match. If not set, the action + specified in the 'action' field will be applied without any + rule checks for the source. + destinations (MutableSequence[google.cloud.network_security_v1.types.AuthorizationPolicy.Rule.Destination]): + Optional. List of attributes for the traffic + destination. All of the destinations must match. + A destination is a match if a request matches + all the specified hosts, ports, methods and + headers. If not set, the action specified in the + 'action' field will be applied without any rule + checks for the destination. + """ + + class Source(proto.Message): + r"""Specification of traffic source attributes. + + Attributes: + principals (MutableSequence[str]): + Optional. List of peer identities to match for + authorization. At least one principal should match. Each + peer can be an exact match, or a prefix match (example, + "namespace/*") or a suffix match (example, + "*/service-account") or a presence match "*". Authorization + based on the principal name without certificate validation + (configured by ServerTlsPolicy resource) is considered + insecure. + ip_blocks (MutableSequence[str]): + Optional. List of CIDR ranges to match based + on source IP address. At least one IP block + should match. Single IP (e.g., "1.2.3.4") and + CIDR (e.g., "1.2.3.0/24") are supported. + Authorization based on source IP alone should be + avoided. The IP addresses of any load balancers + or proxies should be considered untrusted. + """ + + principals: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + ip_blocks: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class Destination(proto.Message): + r"""Specification of traffic destination attributes. + + Attributes: + hosts (MutableSequence[str]): + Required. List of host names to match. Matched against the + ":authority" header in http requests. At least one host + should match. Each host can be an exact match, or a prefix + match (example "mydomain.*") or a suffix match (example + "*.myorg.com") or a presence (any) match "*". + ports (MutableSequence[int]): + Required. List of destination ports to match. + At least one port should match. + methods (MutableSequence[str]): + Optional. A list of HTTP methods to match. At + least one method should match. Should not be set + for gRPC services. + http_header_match (google.cloud.network_security_v1.types.AuthorizationPolicy.Rule.Destination.HttpHeaderMatch): + Optional. Match against key:value pair in + http header. Provides a flexible match based on + HTTP headers, for potentially advanced use + cases. At least one header should match. Avoid + using header matches to make authorization + decisions unless there is a strong guarantee + that requests arrive through a trusted client or + proxy. + """ + + class HttpHeaderMatch(proto.Message): + r"""Specification of HTTP header match attributes. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + regex_match (str): + Required. The value of the header must match + the regular expression specified in regexMatch. + For regular expression grammar, please see: + en.cppreference.com/w/cpp/regex/ecmascript For + matching against a port specified in the HTTP + request, use a headerMatch with headerName set + to Host and a regular expression that satisfies + the RFC2616 Host header's port specifier. + + This field is a member of `oneof`_ ``type``. + header_name (str): + Required. The name of the HTTP header to + match. For matching against the HTTP request's + authority, use a headerMatch with the header + name ":authority". For matching a request's + method, use the headerName ":method". + """ + + regex_match: str = proto.Field( + proto.STRING, + number=2, + oneof='type', + ) + header_name: str = proto.Field( + proto.STRING, + number=1, + ) + + hosts: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + ports: MutableSequence[int] = proto.RepeatedField( + proto.UINT32, + number=2, + ) + methods: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + http_header_match: 'AuthorizationPolicy.Rule.Destination.HttpHeaderMatch' = proto.Field( + proto.MESSAGE, + number=5, + message='AuthorizationPolicy.Rule.Destination.HttpHeaderMatch', + ) + + sources: MutableSequence['AuthorizationPolicy.Rule.Source'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AuthorizationPolicy.Rule.Source', + ) + destinations: MutableSequence['AuthorizationPolicy.Rule.Destination'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AuthorizationPolicy.Rule.Destination', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + action: Action = proto.Field( + proto.ENUM, + number=6, + enum=Action, + ) + rules: MutableSequence[Rule] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Rule, + ) + + +class ListAuthorizationPoliciesRequest(proto.Message): + r"""Request used with the ListAuthorizationPolicies method. + + Attributes: + parent (str): + Required. The project and location from which the + AuthorizationPolicies should be listed, specified in the + format ``projects/{project}/locations/{location}``. + page_size (int): + Maximum number of AuthorizationPolicies to + return per call. + page_token (str): + The value returned by the last + ``ListAuthorizationPoliciesResponse`` Indicates that this is + a continuation of a prior ``ListAuthorizationPolicies`` + call, and that the system should return the next page of + data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAuthorizationPoliciesResponse(proto.Message): + r"""Response returned by the ListAuthorizationPolicies method. + + Attributes: + authorization_policies (MutableSequence[google.cloud.network_security_v1.types.AuthorizationPolicy]): + List of AuthorizationPolicies resources. + next_page_token (str): + If there might be 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 + + authorization_policies: MutableSequence['AuthorizationPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AuthorizationPolicy', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAuthorizationPolicyRequest(proto.Message): + r"""Request used by the GetAuthorizationPolicy method. + + Attributes: + name (str): + Required. A name of the AuthorizationPolicy to get. Must be + in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAuthorizationPolicyRequest(proto.Message): + r"""Request used by the CreateAuthorizationPolicy method. + + Attributes: + parent (str): + Required. The parent resource of the AuthorizationPolicy. + Must be in the format + ``projects/{project}/locations/{location}``. + authorization_policy_id (str): + Required. Short name of the AuthorizationPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and underscores, + and should not start with a number. E.g. "authz_policy". + authorization_policy (google.cloud.network_security_v1.types.AuthorizationPolicy): + Required. AuthorizationPolicy resource to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + authorization_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + authorization_policy: 'AuthorizationPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='AuthorizationPolicy', + ) + + +class UpdateAuthorizationPolicyRequest(proto.Message): + r"""Request used by the UpdateAuthorizationPolicy method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the AuthorizationPolicy resource by the + update. The fields specified in the update_mask are relative + to the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + authorization_policy (google.cloud.network_security_v1.types.AuthorizationPolicy): + Required. Updated AuthorizationPolicy + resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + authorization_policy: 'AuthorizationPolicy' = proto.Field( + proto.MESSAGE, + number=2, + message='AuthorizationPolicy', + ) + + +class DeleteAuthorizationPolicyRequest(proto.Message): + r"""Request used by the DeleteAuthorizationPolicy method. + + Attributes: + name (str): + Required. A name of the AuthorizationPolicy to delete. Must + be in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/client_tls_policy.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/client_tls_policy.py new file mode 100644 index 000000000000..f18aeab942af --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/client_tls_policy.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.network_security_v1.types import tls +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1', + manifest={ + 'ClientTlsPolicy', + 'ListClientTlsPoliciesRequest', + 'ListClientTlsPoliciesResponse', + 'GetClientTlsPolicyRequest', + 'CreateClientTlsPolicyRequest', + 'UpdateClientTlsPolicyRequest', + 'DeleteClientTlsPolicyRequest', + }, +) + + +class ClientTlsPolicy(proto.Message): + r"""ClientTlsPolicy is a resource that specifies how a client + should authenticate connections to backends of a service. This + resource itself does not affect configuration unless it is + attached to a backend service resource. + + Attributes: + name (str): + Required. Name of the ClientTlsPolicy resource. It matches + the pattern + ``projects/*/locations/{location}/clientTlsPolicies/{client_tls_policy}`` + description (str): + Optional. Free-text description of the + resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + labels (MutableMapping[str, str]): + Optional. Set of label tags associated with + the resource. + sni (str): + Optional. Server Name Indication string to + present to the server during TLS handshake. E.g: + "secure.example.com". + client_certificate (google.cloud.network_security_v1.types.CertificateProvider): + Optional. Defines a mechanism to provision + client identity (public and private keys) for + peer to peer authentication. The presence of + this dictates mTLS. + server_validation_ca (MutableSequence[google.cloud.network_security_v1.types.ValidationCA]): + Optional. Defines the mechanism to obtain the + Certificate Authority certificate to validate + the server certificate. If empty, client does + not validate the server certificate. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + sni: str = proto.Field( + proto.STRING, + number=6, + ) + client_certificate: tls.CertificateProvider = proto.Field( + proto.MESSAGE, + number=7, + message=tls.CertificateProvider, + ) + server_validation_ca: MutableSequence[tls.ValidationCA] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=tls.ValidationCA, + ) + + +class ListClientTlsPoliciesRequest(proto.Message): + r"""Request used by the ListClientTlsPolicies method. + + Attributes: + parent (str): + Required. The project and location from which the + ClientTlsPolicies should be listed, specified in the format + ``projects/*/locations/{location}``. + page_size (int): + Maximum number of ClientTlsPolicies to return + per call. + page_token (str): + The value returned by the last + ``ListClientTlsPoliciesResponse`` Indicates that this is a + continuation of a prior ``ListClientTlsPolicies`` call, and + that the system should return the next page of data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListClientTlsPoliciesResponse(proto.Message): + r"""Response returned by the ListClientTlsPolicies method. + + Attributes: + client_tls_policies (MutableSequence[google.cloud.network_security_v1.types.ClientTlsPolicy]): + List of ClientTlsPolicy resources. + next_page_token (str): + If there might be 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 + + client_tls_policies: MutableSequence['ClientTlsPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ClientTlsPolicy', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetClientTlsPolicyRequest(proto.Message): + r"""Request used by the GetClientTlsPolicy method. + + Attributes: + name (str): + Required. A name of the ClientTlsPolicy to get. Must be in + the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateClientTlsPolicyRequest(proto.Message): + r"""Request used by the CreateClientTlsPolicy method. + + Attributes: + parent (str): + Required. The parent resource of the ClientTlsPolicy. Must + be in the format ``projects/*/locations/{location}``. + client_tls_policy_id (str): + Required. Short name of the ClientTlsPolicy resource to be + created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and underscores, + and should not start with a number. E.g. + "client_mtls_policy". + client_tls_policy (google.cloud.network_security_v1.types.ClientTlsPolicy): + Required. ClientTlsPolicy resource to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + client_tls_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + client_tls_policy: 'ClientTlsPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='ClientTlsPolicy', + ) + + +class UpdateClientTlsPolicyRequest(proto.Message): + r"""Request used by UpdateClientTlsPolicy method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ClientTlsPolicy resource by the update. + The fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + client_tls_policy (google.cloud.network_security_v1.types.ClientTlsPolicy): + Required. Updated ClientTlsPolicy resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + client_tls_policy: 'ClientTlsPolicy' = proto.Field( + proto.MESSAGE, + number=2, + message='ClientTlsPolicy', + ) + + +class DeleteClientTlsPolicyRequest(proto.Message): + r"""Request used by the DeleteClientTlsPolicy method. + + Attributes: + name (str): + Required. A name of the ClientTlsPolicy to delete. Must be + in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/common.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/common.py new file mode 100644 index 000000000000..4fa7c372927d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/common.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1', + manifest={ + 'OperationMetadata', + }, +) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have [Operation.error][] value + with a [google.rpc.Status.code][google.rpc.Status.code] of + 1, corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/network_security.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/network_security.py new file mode 100644 index 000000000000..3a1dee864b0f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/network_security.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/server_tls_policy.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/server_tls_policy.py new file mode 100644 index 000000000000..ec702dcdd3d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/server_tls_policy.py @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.network_security_v1.types import tls +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1', + manifest={ + 'ServerTlsPolicy', + 'ListServerTlsPoliciesRequest', + 'ListServerTlsPoliciesResponse', + 'GetServerTlsPolicyRequest', + 'CreateServerTlsPolicyRequest', + 'UpdateServerTlsPolicyRequest', + 'DeleteServerTlsPolicyRequest', + }, +) + + +class ServerTlsPolicy(proto.Message): + r"""ServerTlsPolicy is a resource that specifies how a server + should authenticate incoming requests. This resource itself does + not affect configuration unless it is attached to a target https + proxy or endpoint config selector resource. + + Attributes: + name (str): + Required. Name of the ServerTlsPolicy resource. It matches + the pattern + ``projects/*/locations/{location}/serverTlsPolicies/{server_tls_policy}`` + description (str): + Free-text description of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + labels (MutableMapping[str, str]): + Set of label tags associated with the + resource. + allow_open (bool): + Determines if server allows plaintext connections. If set to + true, server allows plain text connections. By default, it + is set to false. This setting is not exclusive of other + encryption modes. For example, if ``allow_open`` and + ``mtls_policy`` are set, server allows both plain text and + mTLS connections. See documentation of other encryption + modes to confirm compatibility. + + Consider using it if you wish to upgrade in place your + deployment to TLS while having mixed TLS and non-TLS traffic + reaching port :80. + server_certificate (google.cloud.network_security_v1.types.CertificateProvider): + Defines a mechanism to provision server identity (public and + private keys). Cannot be combined with ``allow_open`` as a + permissive mode that allows both plain text and TLS is not + supported. + mtls_policy (google.cloud.network_security_v1.types.ServerTlsPolicy.MTLSPolicy): + Defines a mechanism to provision peer validation + certificates for peer to peer authentication (Mutual TLS - + mTLS). If not specified, client certificate will not be + requested. The connection is treated as TLS and not mTLS. If + ``allow_open`` and ``mtls_policy`` are set, server allows + both plain text and mTLS connections. + """ + + class MTLSPolicy(proto.Message): + r"""Specification of the MTLSPolicy. + + Attributes: + client_validation_ca (MutableSequence[google.cloud.network_security_v1.types.ValidationCA]): + Defines the mechanism to obtain the + Certificate Authority certificate to validate + the client certificate. + """ + + client_validation_ca: MutableSequence[tls.ValidationCA] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=tls.ValidationCA, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + allow_open: bool = proto.Field( + proto.BOOL, + number=6, + ) + server_certificate: tls.CertificateProvider = proto.Field( + proto.MESSAGE, + number=7, + message=tls.CertificateProvider, + ) + mtls_policy: MTLSPolicy = proto.Field( + proto.MESSAGE, + number=8, + message=MTLSPolicy, + ) + + +class ListServerTlsPoliciesRequest(proto.Message): + r"""Request used by the ListServerTlsPolicies method. + + Attributes: + parent (str): + Required. The project and location from which the + ServerTlsPolicies should be listed, specified in the format + ``projects/*/locations/{location}``. + page_size (int): + Maximum number of ServerTlsPolicies to return + per call. + page_token (str): + The value returned by the last + ``ListServerTlsPoliciesResponse`` Indicates that this is a + continuation of a prior ``ListServerTlsPolicies`` call, and + that the system should return the next page of data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServerTlsPoliciesResponse(proto.Message): + r"""Response returned by the ListServerTlsPolicies method. + + Attributes: + server_tls_policies (MutableSequence[google.cloud.network_security_v1.types.ServerTlsPolicy]): + List of ServerTlsPolicy resources. + next_page_token (str): + If there might be 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 + + server_tls_policies: MutableSequence['ServerTlsPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ServerTlsPolicy', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetServerTlsPolicyRequest(proto.Message): + r"""Request used by the GetServerTlsPolicy method. + + Attributes: + name (str): + Required. A name of the ServerTlsPolicy to get. Must be in + the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateServerTlsPolicyRequest(proto.Message): + r"""Request used by the CreateServerTlsPolicy method. + + Attributes: + parent (str): + Required. The parent resource of the ServerTlsPolicy. Must + be in the format ``projects/*/locations/{location}``. + server_tls_policy_id (str): + Required. Short name of the ServerTlsPolicy resource to be + created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and underscores, + and should not start with a number. E.g. + "server_mtls_policy". + server_tls_policy (google.cloud.network_security_v1.types.ServerTlsPolicy): + Required. ServerTlsPolicy resource to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + server_tls_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + server_tls_policy: 'ServerTlsPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='ServerTlsPolicy', + ) + + +class UpdateServerTlsPolicyRequest(proto.Message): + r"""Request used by UpdateServerTlsPolicy method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ServerTlsPolicy resource by the update. + The fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + server_tls_policy (google.cloud.network_security_v1.types.ServerTlsPolicy): + Required. Updated ServerTlsPolicy resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + server_tls_policy: 'ServerTlsPolicy' = proto.Field( + proto.MESSAGE, + number=2, + message='ServerTlsPolicy', + ) + + +class DeleteServerTlsPolicyRequest(proto.Message): + r"""Request used by the DeleteServerTlsPolicy method. + + Attributes: + name (str): + Required. A name of the ServerTlsPolicy to delete. Must be + in the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/tls.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/tls.py new file mode 100644 index 000000000000..c1f555aa255e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/tls.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1', + manifest={ + 'GrpcEndpoint', + 'ValidationCA', + 'CertificateProviderInstance', + 'CertificateProvider', + }, +) + + +class GrpcEndpoint(proto.Message): + r"""Specification of the GRPC Endpoint. + + Attributes: + target_uri (str): + Required. The target URI of the gRPC + endpoint. Only UDS path is supported, and should + start with "unix:". + """ + + target_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ValidationCA(proto.Message): + r"""Specification of ValidationCA. Defines the mechanism to + obtain the Certificate Authority certificate to validate the + peer certificate. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + grpc_endpoint (google.cloud.network_security_v1.types.GrpcEndpoint): + gRPC specific configuration to access the + gRPC server to obtain the CA certificate. + + This field is a member of `oneof`_ ``type``. + certificate_provider_instance (google.cloud.network_security_v1.types.CertificateProviderInstance): + The certificate provider instance + specification that will be passed to the data + plane, which will be used to load necessary + credential information. + + This field is a member of `oneof`_ ``type``. + """ + + grpc_endpoint: 'GrpcEndpoint' = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message='GrpcEndpoint', + ) + certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( + proto.MESSAGE, + number=3, + oneof='type', + message='CertificateProviderInstance', + ) + + +class CertificateProviderInstance(proto.Message): + r"""Specification of a TLS certificate provider instance. + Workloads may have one or more CertificateProvider instances + (plugins) and one of them is enabled and configured by + specifying this message. Workloads use the values from this + message to locate and load the CertificateProvider instance + configuration. + + Attributes: + plugin_instance (str): + Required. Plugin instance name, used to locate and load + CertificateProvider instance configuration. Set to + "google_cloud_private_spiffe" to use Certificate Authority + Service certificate provider instance. + """ + + plugin_instance: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CertificateProvider(proto.Message): + r"""Specification of certificate provider. Defines the mechanism + to obtain the certificate and private key for peer to peer + authentication. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + grpc_endpoint (google.cloud.network_security_v1.types.GrpcEndpoint): + gRPC specific configuration to access the + gRPC server to obtain the cert and private key. + + This field is a member of `oneof`_ ``type``. + certificate_provider_instance (google.cloud.network_security_v1.types.CertificateProviderInstance): + The certificate provider instance + specification that will be passed to the data + plane, which will be used to load necessary + credential information. + + This field is a member of `oneof`_ ``type``. + """ + + grpc_endpoint: 'GrpcEndpoint' = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message='GrpcEndpoint', + ) + certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( + proto.MESSAGE, + number=3, + oneof='type', + message='CertificateProviderInstance', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/mypy.ini b/owl-bot-staging/google-cloud-network-security/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-security/v1/noxfile.py b/owl-bot-staging/google-cloud-network-security/v1/noxfile.py new file mode 100644 index 000000000000..6de174fa4528 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/noxfile.py @@ -0,0 +1,592 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re +import shutil + +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = "google-cloud-network-security" + +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy + "mypy<1.16.0", + "types-requests", + "types-protobuf", + ) + session.install(".") + session.run( + "mypy", + "-p", + "google", + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "update", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "check", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("setuptools", "docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def unit(session, protobuf_implementation): + # Install all test dependencies, then install this package in-place. + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # TODO(https://github.com/googleapis/synthtool/issues/1976): + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +def install_systemtest_dependencies(session, *constraints): + session.install("--pre", "grpcio") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python="3.10") +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.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", ""), + ) + + +@nox.session(python="3.10") +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def prerelease_deps(session, protobuf_implementation): + """ + Run all tests with pre-release versions of dependencies installed + rather than the standard non pre-release versions. + Pre-release versions can be installed using + `pip install --pre `. + """ + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # Note: If a dependency is added to the `prerel_deps` list, + # the `core_dependencies_from_source` list in the `core_deps_from_source` + # nox session should also be updated. + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpc-google-iam-v1", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--ignore-installed", dep) + # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` + # to the dictionary below once this bug is fixed. + # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add + # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below + # once this bug is fixed. + package_namespaces = { + "google-api-core": "google.api_core", + "google-auth": "google.auth", + "grpcio": "grpc", + "protobuf": "google.protobuf", + "proto-plus": "proto", + } + + version_namespace = package_namespaces.get(dep) + + print(f"Installed {dep}") + if version_namespace: + session.run( + "python", + "-c", + f"import {version_namespace}; print({version_namespace}.__version__)", + ) + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb"], +) +def core_deps_from_source(session, protobuf_implementation): + """Run all tests with core dependencies installed from source + rather than pulling the dependencies from PyPI. + """ + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and + # `grpcio-status` should be added to the list below so that they are installed from source, + # rather than PyPI. + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be + # added to the list below so that it is installed from source, rather than PyPI + # Note: If a dependency is added to the `core_dependencies_from_source` list, + # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. + core_dependencies_from_source = [ + "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", + "google-api-core @ git+https://github.com/googleapis/python-api-core.git", + "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", + "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", + "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", + ] + + for dep in core_dependencies_from_source: + session.install(dep, "--no-deps", "--ignore-installed") + print(f"Installed {dep}") + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_async.py new file mode 100644 index 000000000000..f96bcfe72be9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_AddAddressGroupItems_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_add_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.AddAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.add_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_AddAddressGroupItems_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py new file mode 100644 index 000000000000..d5bf351574f8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_AddAddressGroupItems_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_add_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.AddAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.add_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_AddAddressGroupItems_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py new file mode 100644 index 000000000000..d5689f236a08 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CloneAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_CloneAddressGroupItems_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_clone_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CloneAddressGroupItemsRequest( + address_group="address_group_value", + source_address_group="source_address_group_value", + ) + + # Make the request + operation = client.clone_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_CloneAddressGroupItems_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py new file mode 100644 index 000000000000..e612e84413c1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CloneAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_CloneAddressGroupItems_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_clone_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.CloneAddressGroupItemsRequest( + address_group="address_group_value", + source_address_group="source_address_group_value", + ) + + # Make the request + operation = client.clone_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_CloneAddressGroupItems_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_async.py new file mode 100644 index 000000000000..1800eec176a5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_CreateAddressGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_create_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.CreateAddressGroupRequest( + parent="parent_value", + address_group_id="address_group_id_value", + address_group=address_group, + ) + + # Make the request + operation = client.create_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_CreateAddressGroup_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_sync.py new file mode 100644 index 000000000000..e6c93b4de786 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_CreateAddressGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_create_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.CreateAddressGroupRequest( + parent="parent_value", + address_group_id="address_group_id_value", + address_group=address_group, + ) + + # Make the request + operation = client.create_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_CreateAddressGroup_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_async.py new file mode 100644 index 000000000000..d30900c4bd2f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_DeleteAddressGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_delete_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAddressGroupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_DeleteAddressGroup_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_sync.py new file mode 100644 index 000000000000..9b0f11c20b75 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_DeleteAddressGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_delete_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAddressGroupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_DeleteAddressGroup_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_async.py new file mode 100644 index 000000000000..a8d1ceaf8e2e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_GetAddressGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_get_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetAddressGroupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_address_group(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_GetAddressGroup_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_sync.py new file mode 100644 index 000000000000..7868027149aa --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_GetAddressGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_get_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetAddressGroupRequest( + name="name_value", + ) + + # Make the request + response = client.get_address_group(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_GetAddressGroup_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_async.py new file mode 100644 index 000000000000..cd8b3028d6eb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAddressGroupReferences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_ListAddressGroupReferences_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_list_address_group_references(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupReferencesRequest( + address_group="address_group_value", + ) + + # Make the request + page_result = client.list_address_group_references(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_ListAddressGroupReferences_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py new file mode 100644 index 000000000000..84d71c5b9dc8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAddressGroupReferences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_ListAddressGroupReferences_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_list_address_group_references(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupReferencesRequest( + address_group="address_group_value", + ) + + # Make the request + page_result = client.list_address_group_references(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_ListAddressGroupReferences_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_async.py new file mode 100644 index 000000000000..7b58190dd7e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAddressGroups +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_ListAddressGroups_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_list_address_groups(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_address_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_ListAddressGroups_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_sync.py new file mode 100644 index 000000000000..68d95d20d8b4 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAddressGroups +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_ListAddressGroups_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_list_address_groups(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_address_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_ListAddressGroups_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py new file mode 100644 index 000000000000..260c571744bb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_RemoveAddressGroupItems_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_remove_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.RemoveAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.remove_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_RemoveAddressGroupItems_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py new file mode 100644 index 000000000000..4fb42ad1a991 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_RemoveAddressGroupItems_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_remove_address_group_items(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.RemoveAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.remove_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_RemoveAddressGroupItems_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_async.py new file mode 100644 index 000000000000..78191751f385 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_UpdateAddressGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_update_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceAsyncClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.UpdateAddressGroupRequest( + address_group=address_group, + ) + + # Make the request + operation = client.update_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_UpdateAddressGroup_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_sync.py new file mode 100644 index 000000000000..0d1b23d161fe --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_AddressGroupService_UpdateAddressGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_update_address_group(): + # Create a client + client = network_security_v1.AddressGroupServiceClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.UpdateAddressGroupRequest( + address_group=address_group, + ) + + # Make the request + operation = client.update_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_AddressGroupService_UpdateAddressGroup_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_async.py new file mode 100644 index 000000000000..278ecf0b53c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_create_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1.CreateAuthorizationPolicyRequest( + parent="parent_value", + authorization_policy_id="authorization_policy_id_value", + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.create_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_sync.py new file mode 100644 index 000000000000..051baad08806 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_create_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1.CreateAuthorizationPolicyRequest( + parent="parent_value", + authorization_policy_id="authorization_policy_id_value", + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.create_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_async.py new file mode 100644 index 000000000000..0b07d2e09c29 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py new file mode 100644 index 000000000000..071d42cea22a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_async.py new file mode 100644 index 000000000000..612746567f89 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_create_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1.CreateServerTlsPolicyRequest( + parent="parent_value", + server_tls_policy_id="server_tls_policy_id_value", + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.create_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py new file mode 100644 index 000000000000..ed0d9fe82ee7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_create_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1.CreateServerTlsPolicyRequest( + parent="parent_value", + server_tls_policy_id="server_tls_policy_id_value", + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.create_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_async.py new file mode 100644 index 000000000000..3ef46bc6d32b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_delete_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py new file mode 100644 index 000000000000..310ed40682db --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_delete_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py new file mode 100644 index 000000000000..c54c066155b5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py new file mode 100644 index 000000000000..b851622a0786 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py new file mode 100644 index 000000000000..d2098fe79352 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_delete_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py new file mode 100644 index 000000000000..927c9547e922 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_delete_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_async.py new file mode 100644 index 000000000000..44e2152ba3b2 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_get_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_authorization_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_sync.py new file mode 100644 index 000000000000..04deb1cebc7b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_get_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.GetAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_authorization_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_async.py new file mode 100644 index 000000000000..979373defb01 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py new file mode 100644 index 000000000000..f0f70848bb82 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_async.py new file mode 100644 index 000000000000..56f66e7ab8d9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_get_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_server_tls_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py new file mode 100644 index 000000000000..48958304c033 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_get_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.GetServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_server_tls_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_async.py new file mode 100644 index 000000000000..1a160a776672 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAuthorizationPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_list_authorization_policies(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListAuthorizationPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_authorization_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_sync.py new file mode 100644 index 000000000000..714b743f9785 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAuthorizationPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_list_authorization_policies(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.ListAuthorizationPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_authorization_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_async.py new file mode 100644 index 000000000000..02fb1c13e09b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClientTlsPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py new file mode 100644 index 000000000000..490f8df29a4d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClientTlsPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_async.py new file mode 100644 index 000000000000..f89f216a0bb7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServerTlsPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_list_server_tls_policies(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListServerTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_server_tls_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py new file mode 100644 index 000000000000..23d030a39f82 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServerTlsPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_list_server_tls_policies(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1.ListServerTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_server_tls_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_async.py new file mode 100644 index 000000000000..f859337f3e14 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_update_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1.UpdateAuthorizationPolicyRequest( + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.update_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_sync.py new file mode 100644 index 000000000000..5f48db524947 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_update_authorization_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1.UpdateAuthorizationPolicyRequest( + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.update_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_async.py new file mode 100644 index 000000000000..428dfbcad4e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py new file mode 100644 index 000000000000..9d1cf8fa461b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_async.py new file mode 100644 index 000000000000..f86aaa60c9f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_update_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1.UpdateServerTlsPolicyRequest( + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.update_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py new file mode 100644 index 000000000000..7a0fa59f57a1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_update_server_tls_policy(): + # Create a client + client = network_security_v1.NetworkSecurityClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1.UpdateServerTlsPolicyRequest( + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.update_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py new file mode 100644 index 000000000000..8e6047271119 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_add_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.AddAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.add_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py new file mode 100644 index 000000000000..629fb8f427da --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AddAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_add_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.AddAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.add_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py new file mode 100644 index 000000000000..818085904f96 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CloneAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_clone_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.CloneAddressGroupItemsRequest( + address_group="address_group_value", + source_address_group="source_address_group_value", + ) + + # Make the request + operation = client.clone_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py new file mode 100644 index 000000000000..426fee59edc9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CloneAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_clone_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.CloneAddressGroupItemsRequest( + address_group="address_group_value", + source_address_group="source_address_group_value", + ) + + # Make the request + operation = client.clone_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py new file mode 100644 index 000000000000..ef0be464d7e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_create_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.CreateAddressGroupRequest( + parent="parent_value", + address_group_id="address_group_id_value", + address_group=address_group, + ) + + # Make the request + operation = client.create_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py new file mode 100644 index 000000000000..599482e20332 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_create_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.CreateAddressGroupRequest( + parent="parent_value", + address_group_id="address_group_id_value", + address_group=address_group, + ) + + # Make the request + operation = client.create_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py new file mode 100644 index 000000000000..6249ae2e7d89 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_delete_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAddressGroupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py new file mode 100644 index 000000000000..27f9e74b174b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_delete_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.DeleteAddressGroupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py new file mode 100644 index 000000000000..1f329cdff83e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_get_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.GetAddressGroupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_address_group(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py new file mode 100644 index 000000000000..e206366886ba --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_get_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.GetAddressGroupRequest( + name="name_value", + ) + + # Make the request + response = client.get_address_group(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py new file mode 100644 index 000000000000..ec53873674c4 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAddressGroupReferences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_list_address_group_references(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupReferencesRequest( + address_group="address_group_value", + ) + + # Make the request + page_result = client.list_address_group_references(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py new file mode 100644 index 000000000000..d33b76deb47a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAddressGroupReferences +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_list_address_group_references(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupReferencesRequest( + address_group="address_group_value", + ) + + # Make the request + page_result = client.list_address_group_references(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py new file mode 100644 index 000000000000..cd74b2bab2b9 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAddressGroups +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_list_address_groups(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_address_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py new file mode 100644 index 000000000000..b15346366da0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAddressGroups +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_list_address_groups(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.ListAddressGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_address_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py new file mode 100644 index 000000000000..5a816a94ba6c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_remove_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + request = network_security_v1.RemoveAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.remove_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py new file mode 100644 index 000000000000..c898f622ee64 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RemoveAddressGroupItems +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_remove_address_group_items(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + request = network_security_v1.RemoveAddressGroupItemsRequest( + address_group="address_group_value", + items=['items_value1', 'items_value2'], + ) + + # Make the request + operation = client.remove_address_group_items(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py new file mode 100644 index 000000000000..3118386f72a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +async def sample_update_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceAsyncClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.UpdateAddressGroupRequest( + address_group=address_group, + ) + + # Make the request + operation = client.update_address_group(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py new file mode 100644 index 000000000000..402553453df6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAddressGroup +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1 + + +def sample_update_address_group(): + # Create a client + client = network_security_v1.OrganizationAddressGroupServiceClient() + + # Initialize request argument(s) + address_group = network_security_v1.AddressGroup() + address_group.name = "name_value" + address_group.type_ = "IPV6" + address_group.capacity = 846 + + request = network_security_v1.UpdateAddressGroupRequest( + address_group=address_group, + ) + + # Make the request + operation = client.update_address_group(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json new file mode 100644 index 000000000000..ff3746a9796b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json @@ -0,0 +1,5496 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.networksecurity.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-network-security", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.add_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.AddAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "AddAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "items", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "add_address_group_items" + }, + "description": "Sample for AddAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_add_address_group_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_AddAddressGroupItems_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_add_address_group_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.add_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.AddAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "AddAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "items", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "add_address_group_items" + }, + "description": "Sample for AddAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_AddAddressGroupItems_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.clone_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CloneAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "CloneAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "source_address_group", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "clone_address_group_items" + }, + "description": "Sample for CloneAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_CloneAddressGroupItems_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.clone_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CloneAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "CloneAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "source_address_group", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "clone_address_group_items" + }, + "description": "Sample for CloneAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_CloneAddressGroupItems_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.create_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CreateAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "CreateAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "address_group_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_address_group" + }, + "description": "Sample for CreateAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_create_address_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_CreateAddressGroup_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_create_address_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.create_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CreateAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "CreateAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "address_group_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_address_group" + }, + "description": "Sample for CreateAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_create_address_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_CreateAddressGroup_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_create_address_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.delete_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.DeleteAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "DeleteAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_address_group" + }, + "description": "Sample for DeleteAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_delete_address_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_DeleteAddressGroup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_delete_address_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.delete_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.DeleteAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "DeleteAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_address_group" + }, + "description": "Sample for DeleteAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_delete_address_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_DeleteAddressGroup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_delete_address_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.get_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.GetAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "GetAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.AddressGroup", + "shortName": "get_address_group" + }, + "description": "Sample for GetAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_get_address_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_GetAddressGroup_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_get_address_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.get_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.GetAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "GetAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.AddressGroup", + "shortName": "get_address_group" + }, + "description": "Sample for GetAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_get_address_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_GetAddressGroup_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_get_address_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.list_address_group_references", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroupReferences", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "ListAddressGroupReferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupReferencesAsyncPager", + "shortName": "list_address_group_references" + }, + "description": "Sample for ListAddressGroupReferences", + "file": "networksecurity_v1_generated_address_group_service_list_address_group_references_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroupReferences_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_list_address_group_references_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.list_address_group_references", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroupReferences", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "ListAddressGroupReferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupReferencesPager", + "shortName": "list_address_group_references" + }, + "description": "Sample for ListAddressGroupReferences", + "file": "networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroupReferences_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.list_address_groups", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroups", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "ListAddressGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupsAsyncPager", + "shortName": "list_address_groups" + }, + "description": "Sample for ListAddressGroups", + "file": "networksecurity_v1_generated_address_group_service_list_address_groups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroups_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_list_address_groups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.list_address_groups", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroups", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "ListAddressGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupsPager", + "shortName": "list_address_groups" + }, + "description": "Sample for ListAddressGroups", + "file": "networksecurity_v1_generated_address_group_service_list_address_groups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroups_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_list_address_groups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.remove_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.RemoveAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "RemoveAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "items", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "remove_address_group_items" + }, + "description": "Sample for RemoveAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_RemoveAddressGroupItems_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.remove_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.RemoveAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "RemoveAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "items", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "remove_address_group_items" + }, + "description": "Sample for RemoveAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_RemoveAddressGroupItems_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.update_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.UpdateAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "UpdateAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" + }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_address_group" + }, + "description": "Sample for UpdateAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_update_address_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_UpdateAddressGroup_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_update_address_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.update_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.UpdateAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" + }, + "shortName": "UpdateAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" + }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_address_group" + }, + "description": "Sample for UpdateAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_update_address_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_AddressGroupService_UpdateAddressGroup_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_address_group_service_update_address_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "authorization_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_authorization_policy" + }, + "description": "Sample for CreateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "authorization_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_authorization_policy" + }, + "description": "Sample for CreateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "client_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_client_tls_policy" + }, + "description": "Sample for CreateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "client_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_client_tls_policy" + }, + "description": "Sample for CreateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "server_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_server_tls_policy" + }, + "description": "Sample for CreateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "server_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_server_tls_policy" + }, + "description": "Sample for CreateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_authorization_policy" + }, + "description": "Sample for DeleteAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_authorization_policy" + }, + "description": "Sample for DeleteAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_client_tls_policy" + }, + "description": "Sample for DeleteClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_client_tls_policy" + }, + "description": "Sample for DeleteClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_server_tls_policy" + }, + "description": "Sample for DeleteServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_server_tls_policy" + }, + "description": "Sample for DeleteServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", + "shortName": "get_authorization_policy" + }, + "description": "Sample for GetAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", + "shortName": "get_authorization_policy" + }, + "description": "Sample for GetAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", + "shortName": "get_client_tls_policy" + }, + "description": "Sample for GetClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", + "shortName": "get_client_tls_policy" + }, + "description": "Sample for GetClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", + "shortName": "get_server_tls_policy" + }, + "description": "Sample for GetServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", + "shortName": "get_server_tls_policy" + }, + "description": "Sample for GetServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_authorization_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListAuthorizationPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager", + "shortName": "list_authorization_policies" + }, + "description": "Sample for ListAuthorizationPolicies", + "file": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_authorization_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListAuthorizationPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesPager", + "shortName": "list_authorization_policies" + }, + "description": "Sample for ListAuthorizationPolicies", + "file": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_client_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListClientTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager", + "shortName": "list_client_tls_policies" + }, + "description": "Sample for ListClientTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_client_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListClientTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesPager", + "shortName": "list_client_tls_policies" + }, + "description": "Sample for ListClientTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_server_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListServerTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager", + "shortName": "list_server_tls_policies" + }, + "description": "Sample for ListServerTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_server_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListServerTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesPager", + "shortName": "list_server_tls_policies" + }, + "description": "Sample for ListServerTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_authorization_policy" + }, + "description": "Sample for UpdateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_authorization_policy" + }, + "description": "Sample for UpdateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_client_tls_policy" + }, + "description": "Sample for UpdateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_client_tls_policy" + }, + "description": "Sample for UpdateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_server_tls_policy" + }, + "description": "Sample for UpdateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_server_tls_policy" + }, + "description": "Sample for UpdateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.add_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.AddAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "AddAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "items", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "add_address_group_items" + }, + "description": "Sample for AddAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.add_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.AddAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "AddAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "items", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "add_address_group_items" + }, + "description": "Sample for AddAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.clone_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CloneAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "CloneAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "source_address_group", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "clone_address_group_items" + }, + "description": "Sample for CloneAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.clone_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CloneAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "CloneAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "source_address_group", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "clone_address_group_items" + }, + "description": "Sample for CloneAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.create_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CreateAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "CreateAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "address_group_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_address_group" + }, + "description": "Sample for CreateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.create_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CreateAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "CreateAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "address_group_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_address_group" + }, + "description": "Sample for CreateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.delete_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.DeleteAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "DeleteAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_address_group" + }, + "description": "Sample for DeleteAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.delete_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.DeleteAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "DeleteAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_address_group" + }, + "description": "Sample for DeleteAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.get_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.GetAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "GetAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.AddressGroup", + "shortName": "get_address_group" + }, + "description": "Sample for GetAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.get_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.GetAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "GetAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.AddressGroup", + "shortName": "get_address_group" + }, + "description": "Sample for GetAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.list_address_group_references", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroupReferences", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "ListAddressGroupReferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesAsyncPager", + "shortName": "list_address_group_references" + }, + "description": "Sample for ListAddressGroupReferences", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.list_address_group_references", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroupReferences", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "ListAddressGroupReferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesPager", + "shortName": "list_address_group_references" + }, + "description": "Sample for ListAddressGroupReferences", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.list_address_groups", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroups", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "ListAddressGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsAsyncPager", + "shortName": "list_address_groups" + }, + "description": "Sample for ListAddressGroups", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.list_address_groups", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroups", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "ListAddressGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsPager", + "shortName": "list_address_groups" + }, + "description": "Sample for ListAddressGroups", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.remove_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.RemoveAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "RemoveAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "items", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "remove_address_group_items" + }, + "description": "Sample for RemoveAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.remove_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.RemoveAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "RemoveAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "items", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "remove_address_group_items" + }, + "description": "Sample for RemoveAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.update_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.UpdateAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "UpdateAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" + }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_address_group" + }, + "description": "Sample for UpdateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.update_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.UpdateAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "UpdateAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" + }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_address_group" + }, + "description": "Sample for UpdateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-network-security/v1/scripts/fixup_network_security_v1_keywords.py b/owl-bot-staging/google-cloud-network-security/v1/scripts/fixup_network_security_v1_keywords.py new file mode 100644 index 000000000000..4404e816019e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/scripts/fixup_network_security_v1_keywords.py @@ -0,0 +1,199 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 network_securityCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_address_group_items': ('address_group', 'items', 'request_id', ), + 'clone_address_group_items': ('address_group', 'source_address_group', 'request_id', ), + 'create_address_group': ('parent', 'address_group_id', 'address_group', 'request_id', ), + 'create_authorization_policy': ('parent', 'authorization_policy_id', 'authorization_policy', ), + 'create_client_tls_policy': ('parent', 'client_tls_policy_id', 'client_tls_policy', ), + 'create_server_tls_policy': ('parent', 'server_tls_policy_id', 'server_tls_policy', ), + 'delete_address_group': ('name', 'request_id', ), + 'delete_authorization_policy': ('name', ), + 'delete_client_tls_policy': ('name', ), + 'delete_server_tls_policy': ('name', ), + 'get_address_group': ('name', ), + 'get_authorization_policy': ('name', ), + 'get_client_tls_policy': ('name', ), + 'get_server_tls_policy': ('name', ), + 'list_address_group_references': ('address_group', 'page_size', 'page_token', ), + 'list_address_groups': ('parent', 'page_size', 'page_token', 'return_partial_success', ), + 'list_authorization_policies': ('parent', 'page_size', 'page_token', ), + 'list_client_tls_policies': ('parent', 'page_size', 'page_token', ), + 'list_server_tls_policies': ('parent', 'page_size', 'page_token', ), + 'remove_address_group_items': ('address_group', 'items', 'request_id', ), + 'update_address_group': ('address_group', 'update_mask', 'request_id', ), + 'update_authorization_policy': ('authorization_policy', 'update_mask', ), + 'update_client_tls_policy': ('client_tls_policy', 'update_mask', ), + 'update_server_tls_policy': ('server_tls_policy', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=network_securityCallTransformer(), +): + """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 network_security 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/google-cloud-network-security/v1/setup.py b/owl-bot-staging/google-cloud-network-security/v1/setup.py new file mode 100644 index 000000000000..1f618aa7ad2f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-network-security' + + +description = "Google Cloud Network Security API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/network_security/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0", + "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", + "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.14.0, <1.0.0", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2010e549cceb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.13.txt @@ -0,0 +1,12 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +proto-plus>=1 +protobuf>=6 +grpc-google-iam-v1>=0 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..56affbd9bd75 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +grpc-google-iam-v1==0.14.0 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1/tests/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/tests/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_address_group_service.py b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_address_group_service.py new file mode 100644 index 000000000000..54906348d6ad --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_address_group_service.py @@ -0,0 +1,10025 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.network_security_v1.services.address_group_service import AddressGroupServiceAsyncClient +from google.cloud.network_security_v1.services.address_group_service import AddressGroupServiceClient +from google.cloud.network_security_v1.services.address_group_service import pagers +from google.cloud.network_security_v1.services.address_group_service import transports +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import common +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# 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 + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 AddressGroupServiceClient._get_default_mtls_endpoint(None) is None + assert AddressGroupServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AddressGroupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AddressGroupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AddressGroupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AddressGroupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AddressGroupServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AddressGroupServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert AddressGroupServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AddressGroupServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AddressGroupServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert AddressGroupServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert AddressGroupServiceClient._get_client_cert_source(None, False) is None + assert AddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert AddressGroupServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceClient)) +@mock.patch.object(AddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AddressGroupServiceClient._DEFAULT_UNIVERSE + default_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AddressGroupServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + assert AddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "always") == AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + assert AddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + assert AddressGroupServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert AddressGroupServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AddressGroupServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AddressGroupServiceClient._get_universe_domain(None, None) == AddressGroupServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AddressGroupServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = AddressGroupServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = AddressGroupServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (AddressGroupServiceClient, "grpc"), + (AddressGroupServiceAsyncClient, "grpc_asyncio"), + (AddressGroupServiceClient, "rest"), +]) +def test_address_group_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networksecurity.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AddressGroupServiceGrpcTransport, "grpc"), + (transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AddressGroupServiceRestTransport, "rest"), +]) +def test_address_group_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AddressGroupServiceClient, "grpc"), + (AddressGroupServiceAsyncClient, "grpc_asyncio"), + (AddressGroupServiceClient, "rest"), +]) +def test_address_group_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networksecurity.googleapis.com' + ) + + +def test_address_group_service_client_get_transport_class(): + transport = AddressGroupServiceClient.get_transport_class() + available_transports = [ + transports.AddressGroupServiceGrpcTransport, + transports.AddressGroupServiceRestTransport, + ] + assert transport in available_transports + + transport = AddressGroupServiceClient.get_transport_class("grpc") + assert transport == transports.AddressGroupServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc"), + (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AddressGroupServiceClient, transports.AddressGroupServiceRestTransport, "rest"), +]) +@mock.patch.object(AddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceClient)) +@mock.patch.object(AddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceAsyncClient)) +def test_address_group_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(AddressGroupServiceClient, '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(AddressGroupServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc", "true"), + (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc", "false"), + (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AddressGroupServiceClient, transports.AddressGroupServiceRestTransport, "rest", "true"), + (AddressGroupServiceClient, transports.AddressGroupServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceClient)) +@mock.patch.object(AddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_address_group_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + AddressGroupServiceClient, AddressGroupServiceAsyncClient +]) +@mock.patch.object(AddressGroupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AddressGroupServiceClient)) +@mock.patch.object(AddressGroupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AddressGroupServiceAsyncClient)) +def test_address_group_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + AddressGroupServiceClient, AddressGroupServiceAsyncClient +]) +@mock.patch.object(AddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceClient)) +@mock.patch.object(AddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceAsyncClient)) +def test_address_group_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AddressGroupServiceClient._DEFAULT_UNIVERSE + default_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc"), + (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AddressGroupServiceClient, transports.AddressGroupServiceRestTransport, "rest"), +]) +def test_address_group_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc", grpc_helpers), + (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AddressGroupServiceClient, transports.AddressGroupServiceRestTransport, "rest", None), +]) +def test_address_group_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_address_group_service_client_client_options_from_dict(): + with mock.patch('google.cloud.network_security_v1.services.address_group_service.transports.AddressGroupServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AddressGroupServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc", grpc_helpers), + (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_address_group_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networksecurity.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + address_group.ListAddressGroupsRequest, + dict, +]) +def test_list_address_groups(request_type, transport: str = 'grpc'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.ListAddressGroupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = address_group.ListAddressGroupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_address_groups_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = address_group.ListAddressGroupsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_address_groups(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == address_group.ListAddressGroupsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_address_groups_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_address_groups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_address_groups] = mock_rpc + request = {} + client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_address_groups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_address_groups_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_address_groups in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_address_groups] = mock_rpc + + request = {} + await client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_address_groups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_address_groups_async(transport: str = 'grpc_asyncio', request_type=address_group.ListAddressGroupsRequest): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = address_group.ListAddressGroupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_address_groups_async_from_dict(): + await test_list_address_groups_async(request_type=dict) + +def test_list_address_groups_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.ListAddressGroupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + call.return_value = address_group.ListAddressGroupsResponse() + client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_address_groups_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.ListAddressGroupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse()) + await client.list_address_groups(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_address_groups_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.ListAddressGroupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_address_groups( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_address_groups_flattened_error(): + client = AddressGroupServiceClient( + 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_address_groups( + address_group.ListAddressGroupsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_address_groups_flattened_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.ListAddressGroupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_address_groups( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_address_groups_flattened_error_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_address_groups( + address_group.ListAddressGroupsRequest(), + parent='parent_value', + ) + + +def test_list_address_groups_pager(transport_name: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + next_page_token='abc', + ), + address_group.ListAddressGroupsResponse( + address_groups=[], + next_page_token='def', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + ], + next_page_token='ghi', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_address_groups(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, address_group.AddressGroup) + for i in results) +def test_list_address_groups_pages(transport_name: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + next_page_token='abc', + ), + address_group.ListAddressGroupsResponse( + address_groups=[], + next_page_token='def', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + ], + next_page_token='ghi', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_address_groups(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_address_groups_async_pager(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + next_page_token='abc', + ), + address_group.ListAddressGroupsResponse( + address_groups=[], + next_page_token='def', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + ], + next_page_token='ghi', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_address_groups(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, address_group.AddressGroup) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_address_groups_async_pages(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + next_page_token='abc', + ), + address_group.ListAddressGroupsResponse( + address_groups=[], + next_page_token='def', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + ], + next_page_token='ghi', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_address_groups(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + address_group.GetAddressGroupRequest, + dict, +]) +def test_get_address_group(request_type, transport: str = 'grpc'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.AddressGroup( + name='name_value', + description='description_value', + type_=address_group.AddressGroup.Type.IPV4, + items=['items_value'], + capacity=846, + self_link='self_link_value', + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + ) + response = client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = address_group.GetAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, address_group.AddressGroup) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.type_ == address_group.AddressGroup.Type.IPV4 + assert response.items == ['items_value'] + assert response.capacity == 846 + assert response.self_link == 'self_link_value' + assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] + + +def test_get_address_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = address_group.GetAddressGroupRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_address_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == address_group.GetAddressGroupRequest( + name='name_value', + ) + +def test_get_address_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_address_group] = mock_rpc + request = {} + client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_address_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_address_group] = mock_rpc + + request = {} + await client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_address_group_async(transport: str = 'grpc_asyncio', request_type=address_group.GetAddressGroupRequest): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup( + name='name_value', + description='description_value', + type_=address_group.AddressGroup.Type.IPV4, + items=['items_value'], + capacity=846, + self_link='self_link_value', + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + )) + response = await client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = address_group.GetAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, address_group.AddressGroup) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.type_ == address_group.AddressGroup.Type.IPV4 + assert response.items == ['items_value'] + assert response.capacity == 846 + assert response.self_link == 'self_link_value' + assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] + + +@pytest.mark.asyncio +async def test_get_address_group_async_from_dict(): + await test_get_address_group_async(request_type=dict) + +def test_get_address_group_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.GetAddressGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + call.return_value = address_group.AddressGroup() + client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_address_group_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.GetAddressGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup()) + await client.get_address_group(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_address_group_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.AddressGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_address_group( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_address_group_flattened_error(): + client = AddressGroupServiceClient( + 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_address_group( + address_group.GetAddressGroupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_address_group_flattened_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.AddressGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_address_group( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_address_group_flattened_error_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_address_group( + address_group.GetAddressGroupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.CreateAddressGroupRequest, + dict, +]) +def test_create_address_group(request_type, transport: str = 'grpc'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.CreateAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_address_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.CreateAddressGroupRequest( + parent='parent_value', + address_group_id='address_group_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_address_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.CreateAddressGroupRequest( + parent='parent_value', + address_group_id='address_group_id_value', + request_id='request_id_value', + ) + +def test_create_address_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_address_group] = mock_rpc + request = {} + client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_address_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_address_group] = mock_rpc + + request = {} + await client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_address_group_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.CreateAddressGroupRequest): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.CreateAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_address_group_async_from_dict(): + await test_create_address_group_async(request_type=dict) + +def test_create_address_group_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.CreateAddressGroupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_address_group_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.CreateAddressGroupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_address_group(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_address_group_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_address_group( + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].address_group + mock_val = gcn_address_group.AddressGroup(name='name_value') + assert arg == mock_val + arg = args[0].address_group_id + mock_val = 'address_group_id_value' + assert arg == mock_val + + +def test_create_address_group_flattened_error(): + client = AddressGroupServiceClient( + 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_address_group( + gcn_address_group.CreateAddressGroupRequest(), + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + +@pytest.mark.asyncio +async def test_create_address_group_flattened_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_address_group( + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].address_group + mock_val = gcn_address_group.AddressGroup(name='name_value') + assert arg == mock_val + arg = args[0].address_group_id + mock_val = 'address_group_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_address_group_flattened_error_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_address_group( + gcn_address_group.CreateAddressGroupRequest(), + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.UpdateAddressGroupRequest, + dict, +]) +def test_update_address_group(request_type, transport: str = 'grpc'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.UpdateAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_address_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.UpdateAddressGroupRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_address_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.UpdateAddressGroupRequest( + request_id='request_id_value', + ) + +def test_update_address_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_address_group] = mock_rpc + request = {} + client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_address_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_address_group] = mock_rpc + + request = {} + await client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_address_group_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.UpdateAddressGroupRequest): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.UpdateAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_address_group_async_from_dict(): + await test_update_address_group_async(request_type=dict) + +def test_update_address_group_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.UpdateAddressGroupRequest() + + request.address_group.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'address_group.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_address_group_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.UpdateAddressGroupRequest() + + request.address_group.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_address_group(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', + 'address_group.name=name_value', + ) in kw['metadata'] + + +def test_update_address_group_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_address_group( + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = gcn_address_group.AddressGroup(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_address_group_flattened_error(): + client = AddressGroupServiceClient( + 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_address_group( + gcn_address_group.UpdateAddressGroupRequest(), + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_address_group_flattened_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_address_group( + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = gcn_address_group.AddressGroup(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_address_group_flattened_error_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_address_group( + gcn_address_group.UpdateAddressGroupRequest(), + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.AddAddressGroupItemsRequest, + dict, +]) +def test_add_address_group_items(request_type, transport: str = 'grpc'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.AddAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_address_group_items_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.AddAddressGroupItemsRequest( + address_group='address_group_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.add_address_group_items(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.AddAddressGroupItemsRequest( + address_group='address_group_value', + request_id='request_id_value', + ) + +def test_add_address_group_items_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_address_group_items] = mock_rpc + request = {} + client.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_add_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.add_address_group_items in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.add_address_group_items] = mock_rpc + + request = {} + await client.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.add_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_add_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.AddAddressGroupItemsRequest): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__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.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.AddAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_address_group_items_async_from_dict(): + await test_add_address_group_items_async(request_type=dict) + +def test_add_address_group_items_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.AddAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'address_group=address_group_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_address_group_items_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.AddAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_address_group_items(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', + 'address_group=address_group_value', + ) in kw['metadata'] + + +def test_add_address_group_items_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_address_group_items( + address_group='address_group_value', + items=['items_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].items + mock_val = ['items_value'] + assert arg == mock_val + + +def test_add_address_group_items_flattened_error(): + client = AddressGroupServiceClient( + 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.add_address_group_items( + gcn_address_group.AddAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + +@pytest.mark.asyncio +async def test_add_address_group_items_flattened_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_address_group_items( + address_group='address_group_value', + items=['items_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].items + mock_val = ['items_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_address_group_items_flattened_error_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_address_group_items( + gcn_address_group.AddAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.RemoveAddressGroupItemsRequest, + dict, +]) +def test_remove_address_group_items(request_type, transport: str = 'grpc'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.RemoveAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_address_group_items_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.RemoveAddressGroupItemsRequest( + address_group='address_group_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.remove_address_group_items(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.RemoveAddressGroupItemsRequest( + address_group='address_group_value', + request_id='request_id_value', + ) + +def test_remove_address_group_items_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_address_group_items] = mock_rpc + request = {} + client.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.remove_address_group_items in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.remove_address_group_items] = mock_rpc + + request = {} + await client.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.remove_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.RemoveAddressGroupItemsRequest): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__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.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.RemoveAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_address_group_items_async_from_dict(): + await test_remove_address_group_items_async(request_type=dict) + +def test_remove_address_group_items_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.RemoveAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'address_group=address_group_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_address_group_items_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.RemoveAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_address_group_items(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', + 'address_group=address_group_value', + ) in kw['metadata'] + + +def test_remove_address_group_items_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_address_group_items( + address_group='address_group_value', + items=['items_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].items + mock_val = ['items_value'] + assert arg == mock_val + + +def test_remove_address_group_items_flattened_error(): + client = AddressGroupServiceClient( + 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.remove_address_group_items( + gcn_address_group.RemoveAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + +@pytest.mark.asyncio +async def test_remove_address_group_items_flattened_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_address_group_items( + address_group='address_group_value', + items=['items_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].items + mock_val = ['items_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_address_group_items_flattened_error_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_address_group_items( + gcn_address_group.RemoveAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.CloneAddressGroupItemsRequest, + dict, +]) +def test_clone_address_group_items(request_type, transport: str = 'grpc'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.CloneAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_clone_address_group_items_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.CloneAddressGroupItemsRequest( + address_group='address_group_value', + source_address_group='source_address_group_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.clone_address_group_items(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.CloneAddressGroupItemsRequest( + address_group='address_group_value', + source_address_group='source_address_group_value', + request_id='request_id_value', + ) + +def test_clone_address_group_items_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.clone_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.clone_address_group_items] = mock_rpc + request = {} + client.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.clone_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_clone_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.clone_address_group_items in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.clone_address_group_items] = mock_rpc + + request = {} + await client.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.clone_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_clone_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.CloneAddressGroupItemsRequest): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__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.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.CloneAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_clone_address_group_items_async_from_dict(): + await test_clone_address_group_items_async(request_type=dict) + +def test_clone_address_group_items_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.CloneAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'address_group=address_group_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_clone_address_group_items_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.CloneAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.clone_address_group_items(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', + 'address_group=address_group_value', + ) in kw['metadata'] + + +def test_clone_address_group_items_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.clone_address_group_items( + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].source_address_group + mock_val = 'source_address_group_value' + assert arg == mock_val + + +def test_clone_address_group_items_flattened_error(): + client = AddressGroupServiceClient( + 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.clone_address_group_items( + gcn_address_group.CloneAddressGroupItemsRequest(), + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + +@pytest.mark.asyncio +async def test_clone_address_group_items_flattened_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.clone_address_group_items( + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].source_address_group + mock_val = 'source_address_group_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_clone_address_group_items_flattened_error_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.clone_address_group_items( + gcn_address_group.CloneAddressGroupItemsRequest(), + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + + +@pytest.mark.parametrize("request_type", [ + address_group.DeleteAddressGroupRequest, + dict, +]) +def test_delete_address_group(request_type, transport: str = 'grpc'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = address_group.DeleteAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_address_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = address_group.DeleteAddressGroupRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_address_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == address_group.DeleteAddressGroupRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_address_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_address_group] = mock_rpc + request = {} + client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_address_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_address_group] = mock_rpc + + request = {} + await client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_address_group_async(transport: str = 'grpc_asyncio', request_type=address_group.DeleteAddressGroupRequest): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = address_group.DeleteAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_address_group_async_from_dict(): + await test_delete_address_group_async(request_type=dict) + +def test_delete_address_group_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.DeleteAddressGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_address_group_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.DeleteAddressGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_address_group(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_address_group_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_address_group( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_address_group_flattened_error(): + client = AddressGroupServiceClient( + 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_address_group( + address_group.DeleteAddressGroupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_address_group_flattened_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_address_group( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_address_group_flattened_error_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_address_group( + address_group.DeleteAddressGroupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.ListAddressGroupReferencesRequest, + dict, +]) +def test_list_address_group_references(request_type, transport: str = 'grpc'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group_references), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.ListAddressGroupReferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupReferencesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_address_group_references_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.ListAddressGroupReferencesRequest( + address_group='address_group_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_address_group_references(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.ListAddressGroupReferencesRequest( + address_group='address_group_value', + page_token='page_token_value', + ) + +def test_list_address_group_references_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_address_group_references in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_address_group_references] = mock_rpc + request = {} + client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_address_group_references(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_address_group_references_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_address_group_references in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_address_group_references] = mock_rpc + + request = {} + await client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_address_group_references(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_address_group_references_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.ListAddressGroupReferencesRequest): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group_references), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.ListAddressGroupReferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupReferencesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_address_group_references_async_from_dict(): + await test_list_address_group_references_async(request_type=dict) + +def test_list_address_group_references_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.ListAddressGroupReferencesRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() + client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'address_group=address_group_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_address_group_references_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.ListAddressGroupReferencesRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse()) + await client.list_address_group_references(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', + 'address_group=address_group_value', + ) in kw['metadata'] + + +def test_list_address_group_references_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_address_group_references( + address_group='address_group_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + + +def test_list_address_group_references_flattened_error(): + client = AddressGroupServiceClient( + 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_address_group_references( + gcn_address_group.ListAddressGroupReferencesRequest(), + address_group='address_group_value', + ) + +@pytest.mark.asyncio +async def test_list_address_group_references_flattened_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_address_group_references( + address_group='address_group_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_address_group_references_flattened_error_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_address_group_references( + gcn_address_group.ListAddressGroupReferencesRequest(), + address_group='address_group_value', + ) + + +def test_list_address_group_references_pager(transport_name: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='abc', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[], + next_page_token='def', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='ghi', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('address_group', ''), + )), + ) + pager = client.list_address_group_references(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) + for i in results) +def test_list_address_group_references_pages(transport_name: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='abc', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[], + next_page_token='def', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='ghi', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + ), + RuntimeError, + ) + pages = list(client.list_address_group_references(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_address_group_references_async_pager(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='abc', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[], + next_page_token='def', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='ghi', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_address_group_references(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_address_group_references_async_pages(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='abc', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[], + next_page_token='def', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='ghi', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_address_group_references(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_address_groups_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_address_groups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_address_groups] = mock_rpc + + request = {} + client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_address_groups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_address_groups_rest_required_fields(request_type=address_group.ListAddressGroupsRequest): + transport_class = transports.AddressGroupServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_groups._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_groups._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", "return_partial_success", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = address_group.ListAddressGroupsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = address_group.ListAddressGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_address_groups(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_address_groups_rest_unset_required_fields(): + transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_address_groups._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "returnPartialSuccess", )) & set(("parent", ))) + + +def test_list_address_groups_rest_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = address_group.ListAddressGroupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = address_group.ListAddressGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_address_groups(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/addressGroups" % client.transport._host, args[1]) + + +def test_list_address_groups_rest_flattened_error(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_address_groups( + address_group.ListAddressGroupsRequest(), + parent='parent_value', + ) + + +def test_list_address_groups_rest_pager(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + next_page_token='abc', + ), + address_group.ListAddressGroupsResponse( + address_groups=[], + next_page_token='def', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + ], + next_page_token='ghi', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(address_group.ListAddressGroupsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_address_groups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, address_group.AddressGroup) + for i in results) + + pages = list(client.list_address_groups(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_address_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_address_group] = mock_rpc + + request = {} + client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_address_group_rest_required_fields(request_type=address_group.GetAddressGroupRequest): + transport_class = transports.AddressGroupServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_address_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_address_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = address_group.AddressGroup() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = address_group.AddressGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_address_group(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_address_group_rest_unset_required_fields(): + transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_address_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_address_group_rest_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = address_group.AddressGroup() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = address_group.AddressGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_address_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + + +def test_get_address_group_rest_flattened_error(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_address_group( + address_group.GetAddressGroupRequest(), + name='name_value', + ) + + +def test_create_address_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_address_group] = mock_rpc + + request = {} + client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_address_group_rest_required_fields(request_type=gcn_address_group.CreateAddressGroupRequest): + transport_class = transports.AddressGroupServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["address_group_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "addressGroupId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_address_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "addressGroupId" in jsonified_request + assert jsonified_request["addressGroupId"] == request_init["address_group_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["addressGroupId"] = 'address_group_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_address_group._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("address_group_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "addressGroupId" in jsonified_request + assert jsonified_request["addressGroupId"] == 'address_group_id_value' + + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_address_group(request) + + expected_params = [ + ( + "addressGroupId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_address_group_rest_unset_required_fields(): + transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_address_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(("addressGroupId", "requestId", )) & set(("parent", "addressGroupId", "addressGroup", ))) + + +def test_create_address_group_rest_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_address_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/addressGroups" % client.transport._host, args[1]) + + +def test_create_address_group_rest_flattened_error(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_address_group( + gcn_address_group.CreateAddressGroupRequest(), + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + + +def test_update_address_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_address_group] = mock_rpc + + request = {} + client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_address_group_rest_required_fields(request_type=gcn_address_group.UpdateAddressGroupRequest): + transport_class = transports.AddressGroupServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_address_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_address_group._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_address_group(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_address_group_rest_unset_required_fields(): + transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_address_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("addressGroup", ))) + + +def test_update_address_group_rest_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'address_group': {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_address_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{address_group.name=projects/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + + +def test_update_address_group_rest_flattened_error(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_address_group( + gcn_address_group.UpdateAddressGroupRequest(), + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_add_address_group_items_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_address_group_items] = mock_rpc + + request = {} + client.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_add_address_group_items_rest_required_fields(request_type=gcn_address_group.AddAddressGroupItemsRequest): + transport_class = transports.AddressGroupServiceRestTransport + + request_init = {} + request_init["address_group"] = "" + request_init["items"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["addressGroup"] = 'address_group_value' + jsonified_request["items"] = 'items_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "addressGroup" in jsonified_request + assert jsonified_request["addressGroup"] == 'address_group_value' + assert "items" in jsonified_request + assert jsonified_request["items"] == 'items_value' + + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.add_address_group_items(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_add_address_group_items_rest_unset_required_fields(): + transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.add_address_group_items._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("addressGroup", "items", ))) + + +def test_add_address_group_items_rest_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + address_group='address_group_value', + items=['items_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.add_address_group_items(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:addItems" % client.transport._host, args[1]) + + +def test_add_address_group_items_rest_flattened_error(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_address_group_items( + gcn_address_group.AddAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + + +def test_remove_address_group_items_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_address_group_items] = mock_rpc + + request = {} + client.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_remove_address_group_items_rest_required_fields(request_type=gcn_address_group.RemoveAddressGroupItemsRequest): + transport_class = transports.AddressGroupServiceRestTransport + + request_init = {} + request_init["address_group"] = "" + request_init["items"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["addressGroup"] = 'address_group_value' + jsonified_request["items"] = 'items_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "addressGroup" in jsonified_request + assert jsonified_request["addressGroup"] == 'address_group_value' + assert "items" in jsonified_request + assert jsonified_request["items"] == 'items_value' + + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.remove_address_group_items(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_remove_address_group_items_rest_unset_required_fields(): + transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.remove_address_group_items._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("addressGroup", "items", ))) + + +def test_remove_address_group_items_rest_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + address_group='address_group_value', + items=['items_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.remove_address_group_items(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:removeItems" % client.transport._host, args[1]) + + +def test_remove_address_group_items_rest_flattened_error(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_address_group_items( + gcn_address_group.RemoveAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + + +def test_clone_address_group_items_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.clone_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.clone_address_group_items] = mock_rpc + + request = {} + client.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.clone_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_clone_address_group_items_rest_required_fields(request_type=gcn_address_group.CloneAddressGroupItemsRequest): + transport_class = transports.AddressGroupServiceRestTransport + + request_init = {} + request_init["address_group"] = "" + request_init["source_address_group"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clone_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["addressGroup"] = 'address_group_value' + jsonified_request["sourceAddressGroup"] = 'source_address_group_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clone_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "addressGroup" in jsonified_request + assert jsonified_request["addressGroup"] == 'address_group_value' + assert "sourceAddressGroup" in jsonified_request + assert jsonified_request["sourceAddressGroup"] == 'source_address_group_value' + + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.clone_address_group_items(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_clone_address_group_items_rest_unset_required_fields(): + transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.clone_address_group_items._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("addressGroup", "sourceAddressGroup", ))) + + +def test_clone_address_group_items_rest_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.clone_address_group_items(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:cloneItems" % client.transport._host, args[1]) + + +def test_clone_address_group_items_rest_flattened_error(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.clone_address_group_items( + gcn_address_group.CloneAddressGroupItemsRequest(), + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + + +def test_delete_address_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_address_group] = mock_rpc + + request = {} + client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_address_group_rest_required_fields(request_type=address_group.DeleteAddressGroupRequest): + transport_class = transports.AddressGroupServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_address_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_address_group._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_address_group(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_address_group_rest_unset_required_fields(): + transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_address_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +def test_delete_address_group_rest_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_address_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + + +def test_delete_address_group_rest_flattened_error(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_address_group( + address_group.DeleteAddressGroupRequest(), + name='name_value', + ) + + +def test_list_address_group_references_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_address_group_references in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_address_group_references] = mock_rpc + + request = {} + client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_address_group_references(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_address_group_references_rest_required_fields(request_type=gcn_address_group.ListAddressGroupReferencesRequest): + transport_class = transports.AddressGroupServiceRestTransport + + request_init = {} + request_init["address_group"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_group_references._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["addressGroup"] = 'address_group_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_group_references._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "addressGroup" in jsonified_request + assert jsonified_request["addressGroup"] == 'address_group_value' + + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcn_address_group.ListAddressGroupReferencesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_address_group_references(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_address_group_references_rest_unset_required_fields(): + transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_address_group_references._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("addressGroup", ))) + + +def test_list_address_group_references_rest_flattened(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcn_address_group.ListAddressGroupReferencesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + address_group='address_group_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_address_group_references(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:listReferences" % client.transport._host, args[1]) + + +def test_list_address_group_references_rest_flattened_error(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_address_group_references( + gcn_address_group.ListAddressGroupReferencesRequest(), + address_group='address_group_value', + ) + + +def test_list_address_group_references_rest_pager(transport: str = 'rest'): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='abc', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[], + next_page_token='def', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='ghi', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(gcn_address_group.ListAddressGroupReferencesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + + pager = client.list_address_group_references(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) + for i in results) + + pages = list(client.list_address_group_references(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AddressGroupServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AddressGroupServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AddressGroupServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AddressGroupServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AddressGroupServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AddressGroupServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AddressGroupServiceGrpcTransport, + transports.AddressGroupServiceGrpcAsyncIOTransport, + transports.AddressGroupServiceRestTransport, +]) +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_kind_grpc(): + transport = AddressGroupServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_address_groups_empty_call_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + call.return_value = address_group.ListAddressGroupsResponse() + client.list_address_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.ListAddressGroupsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_address_group_empty_call_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + call.return_value = address_group.AddressGroup() + client.get_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.GetAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_address_group_empty_call_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CreateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_address_group_empty_call_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.UpdateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_address_group_items_empty_call_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.AddAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_address_group_items_empty_call_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.RemoveAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_clone_address_group_items_empty_call_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.clone_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CloneAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_address_group_empty_call_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.DeleteAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_address_group_references_empty_call_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() + client.list_address_group_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.ListAddressGroupReferencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AddressGroupServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_address_groups_empty_call_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_address_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.ListAddressGroupsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_address_group_empty_call_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup( + name='name_value', + description='description_value', + type_=address_group.AddressGroup.Type.IPV4, + items=['items_value'], + capacity=846, + self_link='self_link_value', + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + )) + await client.get_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.GetAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_address_group_empty_call_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CreateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_address_group_empty_call_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.UpdateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_address_group_items_empty_call_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.add_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.AddAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_address_group_items_empty_call_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.remove_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.RemoveAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_clone_address_group_items_empty_call_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.clone_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CloneAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_address_group_empty_call_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.DeleteAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_address_group_references_empty_call_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token='next_page_token_value', + )) + await client.list_address_group_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.ListAddressGroupReferencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AddressGroupServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_address_groups_rest_bad_request(request_type=address_group.ListAddressGroupsRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_address_groups(request) + + +@pytest.mark.parametrize("request_type", [ + address_group.ListAddressGroupsRequest, + dict, +]) +def test_list_address_groups_rest_call_success(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = address_group.ListAddressGroupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = address_group.ListAddressGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_address_groups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_address_groups_rest_interceptors(null_interceptor): + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), + ) + client = AddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_list_address_groups") as post, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_list_address_groups_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_list_address_groups") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = address_group.ListAddressGroupsRequest.pb(address_group.ListAddressGroupsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = address_group.ListAddressGroupsResponse.to_json(address_group.ListAddressGroupsResponse()) + req.return_value.content = return_value + + request = address_group.ListAddressGroupsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = address_group.ListAddressGroupsResponse() + post_with_metadata.return_value = address_group.ListAddressGroupsResponse(), metadata + + client.list_address_groups(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_address_group_rest_bad_request(request_type=address_group.GetAddressGroupRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_address_group(request) + + +@pytest.mark.parametrize("request_type", [ + address_group.GetAddressGroupRequest, + dict, +]) +def test_get_address_group_rest_call_success(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = address_group.AddressGroup( + name='name_value', + description='description_value', + type_=address_group.AddressGroup.Type.IPV4, + items=['items_value'], + capacity=846, + self_link='self_link_value', + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = address_group.AddressGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_address_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, address_group.AddressGroup) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.type_ == address_group.AddressGroup.Type.IPV4 + assert response.items == ['items_value'] + assert response.capacity == 846 + assert response.self_link == 'self_link_value' + assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_address_group_rest_interceptors(null_interceptor): + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), + ) + client = AddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_get_address_group") as post, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_get_address_group_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_get_address_group") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = address_group.GetAddressGroupRequest.pb(address_group.GetAddressGroupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = address_group.AddressGroup.to_json(address_group.AddressGroup()) + req.return_value.content = return_value + + request = address_group.GetAddressGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = address_group.AddressGroup() + post_with_metadata.return_value = address_group.AddressGroup(), metadata + + client.get_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_address_group_rest_bad_request(request_type=gcn_address_group.CreateAddressGroupRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_address_group(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.CreateAddressGroupRequest, + dict, +]) +def test_create_address_group_rest_call_success(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["address_group"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'items': ['items_value1', 'items_value2'], 'capacity': 846, 'self_link': 'self_link_value', 'purpose': [1]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_address_group.CreateAddressGroupRequest.meta.fields["address_group"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["address_group"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["address_group"][field])): + del request_init["address_group"][field][i][subfield] + else: + del request_init["address_group"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_address_group(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_address_group_rest_interceptors(null_interceptor): + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), + ) + client = AddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_create_address_group") as post, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_create_address_group_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_create_address_group") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.CreateAddressGroupRequest.pb(gcn_address_group.CreateAddressGroupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_address_group.CreateAddressGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_address_group_rest_bad_request(request_type=gcn_address_group.UpdateAddressGroupRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'address_group': {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_address_group(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.UpdateAddressGroupRequest, + dict, +]) +def test_update_address_group_rest_call_success(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'address_group': {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'}} + request_init["address_group"] = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'items': ['items_value1', 'items_value2'], 'capacity': 846, 'self_link': 'self_link_value', 'purpose': [1]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_address_group.UpdateAddressGroupRequest.meta.fields["address_group"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["address_group"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["address_group"][field])): + del request_init["address_group"][field][i][subfield] + else: + del request_init["address_group"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_address_group(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_address_group_rest_interceptors(null_interceptor): + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), + ) + client = AddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_update_address_group") as post, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_update_address_group_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_update_address_group") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.UpdateAddressGroupRequest.pb(gcn_address_group.UpdateAddressGroupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_address_group.UpdateAddressGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_add_address_group_items_rest_bad_request(request_type=gcn_address_group.AddAddressGroupItemsRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.add_address_group_items(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.AddAddressGroupItemsRequest, + dict, +]) +def test_add_address_group_items_rest_call_success(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.add_address_group_items(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_address_group_items_rest_interceptors(null_interceptor): + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), + ) + client = AddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_add_address_group_items") as post, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_add_address_group_items_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_add_address_group_items") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.AddAddressGroupItemsRequest.pb(gcn_address_group.AddAddressGroupItemsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_address_group.AddAddressGroupItemsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.add_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_remove_address_group_items_rest_bad_request(request_type=gcn_address_group.RemoveAddressGroupItemsRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.remove_address_group_items(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.RemoveAddressGroupItemsRequest, + dict, +]) +def test_remove_address_group_items_rest_call_success(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.remove_address_group_items(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_address_group_items_rest_interceptors(null_interceptor): + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), + ) + client = AddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_remove_address_group_items") as post, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_remove_address_group_items_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_remove_address_group_items") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.RemoveAddressGroupItemsRequest.pb(gcn_address_group.RemoveAddressGroupItemsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_address_group.RemoveAddressGroupItemsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.remove_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_clone_address_group_items_rest_bad_request(request_type=gcn_address_group.CloneAddressGroupItemsRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.clone_address_group_items(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.CloneAddressGroupItemsRequest, + dict, +]) +def test_clone_address_group_items_rest_call_success(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.clone_address_group_items(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_clone_address_group_items_rest_interceptors(null_interceptor): + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), + ) + client = AddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_clone_address_group_items") as post, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_clone_address_group_items_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_clone_address_group_items") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.CloneAddressGroupItemsRequest.pb(gcn_address_group.CloneAddressGroupItemsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_address_group.CloneAddressGroupItemsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.clone_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_address_group_rest_bad_request(request_type=address_group.DeleteAddressGroupRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_address_group(request) + + +@pytest.mark.parametrize("request_type", [ + address_group.DeleteAddressGroupRequest, + dict, +]) +def test_delete_address_group_rest_call_success(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_address_group(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_address_group_rest_interceptors(null_interceptor): + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), + ) + client = AddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_delete_address_group") as post, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_delete_address_group_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_delete_address_group") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = address_group.DeleteAddressGroupRequest.pb(address_group.DeleteAddressGroupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = address_group.DeleteAddressGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_address_group_references_rest_bad_request(request_type=gcn_address_group.ListAddressGroupReferencesRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_address_group_references(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.ListAddressGroupReferencesRequest, + dict, +]) +def test_list_address_group_references_rest_call_success(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_address_group_references(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupReferencesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_address_group_references_rest_interceptors(null_interceptor): + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), + ) + client = AddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_list_address_group_references") as post, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_list_address_group_references_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_list_address_group_references") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.ListAddressGroupReferencesRequest.pb(gcn_address_group.ListAddressGroupReferencesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcn_address_group.ListAddressGroupReferencesResponse.to_json(gcn_address_group.ListAddressGroupReferencesResponse()) + req.return_value.content = return_value + + request = gcn_address_group.ListAddressGroupReferencesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcn_address_group.ListAddressGroupReferencesResponse() + post_with_metadata.return_value = gcn_address_group.ListAddressGroupReferencesResponse(), metadata + + client.list_address_group_references(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_initialize_client_w_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_address_groups_empty_call_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + client.list_address_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.ListAddressGroupsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_address_group_empty_call_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + client.get_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.GetAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_address_group_empty_call_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + client.create_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CreateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_address_group_empty_call_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + client.update_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.UpdateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_address_group_items_empty_call_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + client.add_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.AddAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_address_group_items_empty_call_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + client.remove_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.RemoveAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_clone_address_group_items_empty_call_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + client.clone_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CloneAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_address_group_empty_call_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + client.delete_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.DeleteAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_address_group_references_empty_call_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + client.list_address_group_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.ListAddressGroupReferencesRequest() + + assert args[0] == request_msg + + +def test_address_group_service_rest_lro_client(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, +operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AddressGroupServiceGrpcTransport, + ) + +def test_address_group_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AddressGroupServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_address_group_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.network_security_v1.services.address_group_service.transports.AddressGroupServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AddressGroupServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_address_groups', + 'get_address_group', + 'create_address_group', + 'update_address_group', + 'add_address_group_items', + 'remove_address_group_items', + 'clone_address_group_items', + 'delete_address_group', + 'list_address_group_references', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_address_group_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.network_security_v1.services.address_group_service.transports.AddressGroupServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AddressGroupServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_address_group_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.network_security_v1.services.address_group_service.transports.AddressGroupServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AddressGroupServiceTransport() + adc.assert_called_once() + + +def test_address_group_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) + AddressGroupServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AddressGroupServiceGrpcTransport, + transports.AddressGroupServiceGrpcAsyncIOTransport, + ], +) +def test_address_group_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.AddressGroupServiceGrpcTransport, + transports.AddressGroupServiceGrpcAsyncIOTransport, + transports.AddressGroupServiceRestTransport, + ], +) +def test_address_group_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AddressGroupServiceGrpcTransport, grpc_helpers), + (transports.AddressGroupServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_address_group_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( + "networksecurity.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="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AddressGroupServiceGrpcTransport, transports.AddressGroupServiceGrpcAsyncIOTransport]) +def test_address_group_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_address_group_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.AddressGroupServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_address_group_service_host_no_port(transport_name): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networksecurity.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_address_group_service_host_with_port(transport_name): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networksecurity.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networksecurity.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_address_group_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AddressGroupServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AddressGroupServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_address_groups._session + session2 = client2.transport.list_address_groups._session + assert session1 != session2 + session1 = client1.transport.get_address_group._session + session2 = client2.transport.get_address_group._session + assert session1 != session2 + session1 = client1.transport.create_address_group._session + session2 = client2.transport.create_address_group._session + assert session1 != session2 + session1 = client1.transport.update_address_group._session + session2 = client2.transport.update_address_group._session + assert session1 != session2 + session1 = client1.transport.add_address_group_items._session + session2 = client2.transport.add_address_group_items._session + assert session1 != session2 + session1 = client1.transport.remove_address_group_items._session + session2 = client2.transport.remove_address_group_items._session + assert session1 != session2 + session1 = client1.transport.clone_address_group_items._session + session2 = client2.transport.clone_address_group_items._session + assert session1 != session2 + session1 = client1.transport.delete_address_group._session + session2 = client2.transport.delete_address_group._session + assert session1 != session2 + session1 = client1.transport.list_address_group_references._session + session2 = client2.transport.list_address_group_references._session + assert session1 != session2 +def test_address_group_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AddressGroupServiceGrpcTransport( + 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_address_group_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AddressGroupServiceGrpcAsyncIOTransport( + 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.AddressGroupServiceGrpcTransport, transports.AddressGroupServiceGrpcAsyncIOTransport]) +def test_address_group_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.AddressGroupServiceGrpcTransport, transports.AddressGroupServiceGrpcAsyncIOTransport]) +def test_address_group_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_address_group_service_grpc_lro_client(): + client = AddressGroupServiceClient( + 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_address_group_service_grpc_lro_async_client(): + client = AddressGroupServiceAsyncClient( + 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_address_group_path(): + project = "squid" + location = "clam" + address_group = "whelk" + expected = "projects/{project}/locations/{location}/addressGroups/{address_group}".format(project=project, location=location, address_group=address_group, ) + actual = AddressGroupServiceClient.address_group_path(project, location, address_group) + assert expected == actual + + +def test_parse_address_group_path(): + expected = { + "project": "octopus", + "location": "oyster", + "address_group": "nudibranch", + } + path = AddressGroupServiceClient.address_group_path(**expected) + + # Check that the path construction is reversible. + actual = AddressGroupServiceClient.parse_address_group_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AddressGroupServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = AddressGroupServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AddressGroupServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = AddressGroupServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = AddressGroupServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AddressGroupServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AddressGroupServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = AddressGroupServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AddressGroupServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = AddressGroupServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = AddressGroupServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AddressGroupServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AddressGroupServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = AddressGroupServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AddressGroupServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.AddressGroupServiceTransport, '_prep_wrapped_messages') as prep: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AddressGroupServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AddressGroupServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = AddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport), + (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_network_security.py b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_network_security.py new file mode 100644 index 000000000000..6df5103b049b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_network_security.py @@ -0,0 +1,14565 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.network_security_v1.services.network_security import NetworkSecurityAsyncClient +from google.cloud.network_security_v1.services.network_security import NetworkSecurityClient +from google.cloud.network_security_v1.services.network_security import pagers +from google.cloud.network_security_v1.services.network_security import transports +from google.cloud.network_security_v1.types import authorization_policy +from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1.types import client_tls_policy +from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1.types import common +from google.cloud.network_security_v1.types import server_tls_policy +from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy +from google.cloud.network_security_v1.types import tls +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# 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 + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 NetworkSecurityClient._get_default_mtls_endpoint(None) is None + assert NetworkSecurityClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert NetworkSecurityClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + NetworkSecurityClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + NetworkSecurityClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert NetworkSecurityClient._get_client_cert_source(None, False) is None + assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert NetworkSecurityClient._get_client_cert_source(None, True) is mock_default_cert_source + assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE + default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert NetworkSecurityClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + assert NetworkSecurityClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert NetworkSecurityClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert NetworkSecurityClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert NetworkSecurityClient._get_universe_domain(None, None) == NetworkSecurityClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + NetworkSecurityClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = NetworkSecurityClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = NetworkSecurityClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (NetworkSecurityClient, "grpc"), + (NetworkSecurityAsyncClient, "grpc_asyncio"), + (NetworkSecurityClient, "rest"), +]) +def test_network_security_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networksecurity.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.NetworkSecurityGrpcTransport, "grpc"), + (transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.NetworkSecurityRestTransport, "rest"), +]) +def test_network_security_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (NetworkSecurityClient, "grpc"), + (NetworkSecurityAsyncClient, "grpc_asyncio"), + (NetworkSecurityClient, "rest"), +]) +def test_network_security_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networksecurity.googleapis.com' + ) + + +def test_network_security_client_get_transport_class(): + transport = NetworkSecurityClient.get_transport_class() + available_transports = [ + transports.NetworkSecurityGrpcTransport, + transports.NetworkSecurityRestTransport, + ] + assert transport in available_transports + + transport = NetworkSecurityClient.get_transport_class("grpc") + assert transport == transports.NetworkSecurityGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"), +]) +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +def test_network_security_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(NetworkSecurityClient, '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(NetworkSecurityClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "true"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "false"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", "true"), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", "false"), +]) +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_network_security_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + NetworkSecurityClient, NetworkSecurityAsyncClient +]) +@mock.patch.object(NetworkSecurityClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityAsyncClient)) +def test_network_security_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + NetworkSecurityClient, NetworkSecurityAsyncClient +]) +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +def test_network_security_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE + default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"), +]) +def test_network_security_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", None), +]) +def test_network_security_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_network_security_client_client_options_from_dict(): + with mock.patch('google.cloud.network_security_v1.services.network_security.transports.NetworkSecurityGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = NetworkSecurityClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_network_security_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networksecurity.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + authorization_policy.ListAuthorizationPoliciesRequest, + dict, +]) +def test_list_authorization_policies(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_authorization_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = authorization_policy.ListAuthorizationPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthorizationPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_authorization_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = authorization_policy.ListAuthorizationPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_authorization_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == authorization_policy.ListAuthorizationPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_authorization_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_authorization_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_authorization_policies] = mock_rpc + request = {} + client.list_authorization_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_authorization_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_authorization_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_authorization_policies in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_authorization_policies] = mock_rpc + + request = {} + await client.list_authorization_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_authorization_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_authorization_policies_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.ListAuthorizationPoliciesRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_authorization_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = authorization_policy.ListAuthorizationPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthorizationPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_authorization_policies_async_from_dict(): + await test_list_authorization_policies_async(request_type=dict) + +def test_list_authorization_policies_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.ListAuthorizationPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + client.list_authorization_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_authorization_policies_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.ListAuthorizationPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse()) + await client.list_authorization_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_authorization_policies_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_authorization_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_authorization_policies_flattened_error(): + client = NetworkSecurityClient( + 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_authorization_policies( + authorization_policy.ListAuthorizationPoliciesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_authorization_policies_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_authorization_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_authorization_policies_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_authorization_policies( + authorization_policy.ListAuthorizationPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_authorization_policies_pager(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='abc', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[], + next_page_token='def', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='ghi', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_authorization_policies(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, authorization_policy.AuthorizationPolicy) + for i in results) +def test_list_authorization_policies_pages(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='abc', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[], + next_page_token='def', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='ghi', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_authorization_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_list_authorization_policies_async_pager(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='abc', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[], + next_page_token='def', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='ghi', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_authorization_policies(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, authorization_policy.AuthorizationPolicy) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_authorization_policies_async_pages(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='abc', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[], + next_page_token='def', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='ghi', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_authorization_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + authorization_policy.GetAuthorizationPolicyRequest, + dict, +]) +def test_get_authorization_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.AuthorizationPolicy( + name='name_value', + description='description_value', + action=authorization_policy.AuthorizationPolicy.Action.ALLOW, + ) + response = client.get_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = authorization_policy.GetAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, authorization_policy.AuthorizationPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW + + +def test_get_authorization_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = authorization_policy.GetAuthorizationPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_authorization_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == authorization_policy.GetAuthorizationPolicyRequest( + name='name_value', + ) + +def test_get_authorization_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_authorization_policy] = mock_rpc + request = {} + client.get_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_authorization_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_authorization_policy] = mock_rpc + + request = {} + await client.get_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.GetAuthorizationPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy( + name='name_value', + description='description_value', + action=authorization_policy.AuthorizationPolicy.Action.ALLOW, + )) + response = await client.get_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = authorization_policy.GetAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, authorization_policy.AuthorizationPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW + + +@pytest.mark.asyncio +async def test_get_authorization_policy_async_from_dict(): + await test_get_authorization_policy_async(request_type=dict) + +def test_get_authorization_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.GetAuthorizationPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + call.return_value = authorization_policy.AuthorizationPolicy() + client.get_authorization_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_authorization_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.GetAuthorizationPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy()) + await client.get_authorization_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_authorization_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.AuthorizationPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_authorization_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_authorization_policy_flattened_error(): + client = NetworkSecurityClient( + 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_authorization_policy( + authorization_policy.GetAuthorizationPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_authorization_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.AuthorizationPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_authorization_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_authorization_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_authorization_policy( + authorization_policy.GetAuthorizationPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_authorization_policy.CreateAuthorizationPolicyRequest, + dict, +]) +def test_create_authorization_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_authorization_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest( + parent='parent_value', + authorization_policy_id='authorization_policy_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_authorization_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_authorization_policy.CreateAuthorizationPolicyRequest( + parent='parent_value', + authorization_policy_id='authorization_policy_id_value', + ) + +def test_create_authorization_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_authorization_policy] = mock_rpc + request = {} + client.create_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_authorization_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_authorization_policy] = mock_rpc + + request = {} + await client.create_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_authorization_policy_async_from_dict(): + await test_create_authorization_policy_async(request_type=dict) + +def test_create_authorization_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_authorization_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_authorization_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_authorization_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_authorization_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_authorization_policy( + parent='parent_value', + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + authorization_policy_id='authorization_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].authorization_policy + mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') + assert arg == mock_val + arg = args[0].authorization_policy_id + mock_val = 'authorization_policy_id_value' + assert arg == mock_val + + +def test_create_authorization_policy_flattened_error(): + client = NetworkSecurityClient( + 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_authorization_policy( + gcn_authorization_policy.CreateAuthorizationPolicyRequest(), + parent='parent_value', + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + authorization_policy_id='authorization_policy_id_value', + ) + +@pytest.mark.asyncio +async def test_create_authorization_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_authorization_policy( + parent='parent_value', + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + authorization_policy_id='authorization_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].authorization_policy + mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') + assert arg == mock_val + arg = args[0].authorization_policy_id + mock_val = 'authorization_policy_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_authorization_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_authorization_policy( + gcn_authorization_policy.CreateAuthorizationPolicyRequest(), + parent='parent_value', + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + authorization_policy_id='authorization_policy_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_authorization_policy.UpdateAuthorizationPolicyRequest, + dict, +]) +def test_update_authorization_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_authorization_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_authorization_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_authorization_policy.UpdateAuthorizationPolicyRequest( + ) + +def test_update_authorization_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_authorization_policy] = mock_rpc + request = {} + client.update_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_authorization_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_authorization_policy] = mock_rpc + + request = {} + await client.update_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_authorization_policy_async_from_dict(): + await test_update_authorization_policy_async(request_type=dict) + +def test_update_authorization_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + request.authorization_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_authorization_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', + 'authorization_policy.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_authorization_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + request.authorization_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_authorization_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', + 'authorization_policy.name=name_value', + ) in kw['metadata'] + + +def test_update_authorization_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_authorization_policy( + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].authorization_policy + mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_authorization_policy_flattened_error(): + client = NetworkSecurityClient( + 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_authorization_policy( + gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_authorization_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_authorization_policy( + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].authorization_policy + mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_authorization_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_authorization_policy( + gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + authorization_policy.DeleteAuthorizationPolicyRequest, + dict, +]) +def test_delete_authorization_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = authorization_policy.DeleteAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_authorization_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = authorization_policy.DeleteAuthorizationPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_authorization_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == authorization_policy.DeleteAuthorizationPolicyRequest( + name='name_value', + ) + +def test_delete_authorization_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_authorization_policy] = mock_rpc + request = {} + client.delete_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_authorization_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_authorization_policy] = mock_rpc + + request = {} + await client.delete_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.DeleteAuthorizationPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = authorization_policy.DeleteAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_authorization_policy_async_from_dict(): + await test_delete_authorization_policy_async(request_type=dict) + +def test_delete_authorization_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.DeleteAuthorizationPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_authorization_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_authorization_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.DeleteAuthorizationPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_authorization_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_authorization_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_authorization_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_authorization_policy_flattened_error(): + client = NetworkSecurityClient( + 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_authorization_policy( + authorization_policy.DeleteAuthorizationPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_authorization_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_authorization_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_authorization_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_authorization_policy( + authorization_policy.DeleteAuthorizationPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + server_tls_policy.ListServerTlsPoliciesRequest, + dict, +]) +def test_list_server_tls_policies(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_server_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = server_tls_policy.ListServerTlsPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServerTlsPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_server_tls_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = server_tls_policy.ListServerTlsPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_server_tls_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == server_tls_policy.ListServerTlsPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_server_tls_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_server_tls_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_server_tls_policies] = mock_rpc + request = {} + client.list_server_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_server_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_server_tls_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_server_tls_policies in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_server_tls_policies] = mock_rpc + + request = {} + await client.list_server_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_server_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_server_tls_policies_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.ListServerTlsPoliciesRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_server_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = server_tls_policy.ListServerTlsPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServerTlsPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_server_tls_policies_async_from_dict(): + await test_list_server_tls_policies_async(request_type=dict) + +def test_list_server_tls_policies_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.ListServerTlsPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + client.list_server_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_server_tls_policies_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.ListServerTlsPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse()) + await client.list_server_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_server_tls_policies_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_server_tls_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_server_tls_policies_flattened_error(): + client = NetworkSecurityClient( + 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_server_tls_policies( + server_tls_policy.ListServerTlsPoliciesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_server_tls_policies_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_server_tls_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_server_tls_policies_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_server_tls_policies( + server_tls_policy.ListServerTlsPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_server_tls_policies_pager(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='abc', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[], + next_page_token='def', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='ghi', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_server_tls_policies(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) + for i in results) +def test_list_server_tls_policies_pages(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='abc', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[], + next_page_token='def', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='ghi', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_server_tls_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_list_server_tls_policies_async_pager(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='abc', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[], + next_page_token='def', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='ghi', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_server_tls_policies(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_server_tls_policies_async_pages(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='abc', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[], + next_page_token='def', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='ghi', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_server_tls_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + server_tls_policy.GetServerTlsPolicyRequest, + dict, +]) +def test_get_server_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ServerTlsPolicy( + name='name_value', + description='description_value', + allow_open=True, + ) + response = client.get_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = server_tls_policy.GetServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, server_tls_policy.ServerTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.allow_open is True + + +def test_get_server_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = server_tls_policy.GetServerTlsPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_server_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == server_tls_policy.GetServerTlsPolicyRequest( + name='name_value', + ) + +def test_get_server_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_server_tls_policy] = mock_rpc + request = {} + client.get_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_server_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_server_tls_policy] = mock_rpc + + request = {} + await client.get_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.GetServerTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy( + name='name_value', + description='description_value', + allow_open=True, + )) + response = await client.get_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = server_tls_policy.GetServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, server_tls_policy.ServerTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.allow_open is True + + +@pytest.mark.asyncio +async def test_get_server_tls_policy_async_from_dict(): + await test_get_server_tls_policy_async(request_type=dict) + +def test_get_server_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.GetServerTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + call.return_value = server_tls_policy.ServerTlsPolicy() + client.get_server_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_server_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.GetServerTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy()) + await client.get_server_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_server_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ServerTlsPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_server_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_server_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_server_tls_policy( + server_tls_policy.GetServerTlsPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_server_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ServerTlsPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_server_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_server_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_server_tls_policy( + server_tls_policy.GetServerTlsPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_server_tls_policy.CreateServerTlsPolicyRequest, + dict, +]) +def test_create_server_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_server_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest( + parent='parent_value', + server_tls_policy_id='server_tls_policy_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_server_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_server_tls_policy.CreateServerTlsPolicyRequest( + parent='parent_value', + server_tls_policy_id='server_tls_policy_id_value', + ) + +def test_create_server_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_server_tls_policy] = mock_rpc + request = {} + client.create_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_server_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_server_tls_policy] = mock_rpc + + request = {} + await client.create_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_server_tls_policy_async_from_dict(): + await test_create_server_tls_policy_async(request_type=dict) + +def test_create_server_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_server_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_server_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_server_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_server_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_server_tls_policy( + parent='parent_value', + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + server_tls_policy_id='server_tls_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].server_tls_policy + mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].server_tls_policy_id + mock_val = 'server_tls_policy_id_value' + assert arg == mock_val + + +def test_create_server_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_server_tls_policy( + gcn_server_tls_policy.CreateServerTlsPolicyRequest(), + parent='parent_value', + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + server_tls_policy_id='server_tls_policy_id_value', + ) + +@pytest.mark.asyncio +async def test_create_server_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_server_tls_policy( + parent='parent_value', + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + server_tls_policy_id='server_tls_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].server_tls_policy + mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].server_tls_policy_id + mock_val = 'server_tls_policy_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_server_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_server_tls_policy( + gcn_server_tls_policy.CreateServerTlsPolicyRequest(), + parent='parent_value', + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + server_tls_policy_id='server_tls_policy_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_server_tls_policy.UpdateServerTlsPolicyRequest, + dict, +]) +def test_update_server_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_server_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_server_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_server_tls_policy.UpdateServerTlsPolicyRequest( + ) + +def test_update_server_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_server_tls_policy] = mock_rpc + request = {} + client.update_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_server_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_server_tls_policy] = mock_rpc + + request = {} + await client.update_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_server_tls_policy_async_from_dict(): + await test_update_server_tls_policy_async(request_type=dict) + +def test_update_server_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + request.server_tls_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_server_tls_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', + 'server_tls_policy.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_server_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + request.server_tls_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_server_tls_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', + 'server_tls_policy.name=name_value', + ) in kw['metadata'] + + +def test_update_server_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_server_tls_policy( + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].server_tls_policy + mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_server_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_server_tls_policy( + gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_server_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_server_tls_policy( + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].server_tls_policy + mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_server_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_server_tls_policy( + gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + server_tls_policy.DeleteServerTlsPolicyRequest, + dict, +]) +def test_delete_server_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = server_tls_policy.DeleteServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_server_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = server_tls_policy.DeleteServerTlsPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_server_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == server_tls_policy.DeleteServerTlsPolicyRequest( + name='name_value', + ) + +def test_delete_server_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_server_tls_policy] = mock_rpc + request = {} + client.delete_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_server_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_server_tls_policy] = mock_rpc + + request = {} + await client.delete_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.DeleteServerTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = server_tls_policy.DeleteServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_async_from_dict(): + await test_delete_server_tls_policy_async(request_type=dict) + +def test_delete_server_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.DeleteServerTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_server_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.DeleteServerTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_server_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_server_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_server_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_server_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_server_tls_policy( + server_tls_policy.DeleteServerTlsPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_server_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_server_tls_policy( + server_tls_policy.DeleteServerTlsPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.ListClientTlsPoliciesRequest, + dict, +]) +def test_list_client_tls_policies(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = client_tls_policy.ListClientTlsPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClientTlsPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_client_tls_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = client_tls_policy.ListClientTlsPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_client_tls_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == client_tls_policy.ListClientTlsPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_client_tls_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_client_tls_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_client_tls_policies] = mock_rpc + request = {} + client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_client_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_client_tls_policies in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_client_tls_policies] = mock_rpc + + request = {} + await client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_client_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.ListClientTlsPoliciesRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = client_tls_policy.ListClientTlsPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClientTlsPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async_from_dict(): + await test_list_client_tls_policies_async(request_type=dict) + +def test_list_client_tls_policies_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.ListClientTlsPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + client.list_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_client_tls_policies_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.ListClientTlsPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) + await client.list_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_client_tls_policies_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_client_tls_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_client_tls_policies_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policies( + client_tls_policy.ListClientTlsPoliciesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_client_tls_policies_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_client_tls_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_client_tls_policies_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_client_tls_policies( + client_tls_policy.ListClientTlsPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_client_tls_policies_pager(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_client_tls_policies(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) + for i in results) +def test_list_client_tls_policies_pages(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_client_tls_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_list_client_tls_policies_async_pager(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_client_tls_policies(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async_pages(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_client_tls_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.GetClientTlsPolicyRequest, + dict, +]) +def test_get_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + ) + response = client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = client_tls_policy.GetClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, client_tls_policy.ClientTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.sni == 'sni_value' + + +def test_get_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = client_tls_policy.GetClientTlsPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == client_tls_policy.GetClientTlsPolicyRequest( + name='name_value', + ) + +def test_get_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_client_tls_policy] = mock_rpc + request = {} + client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_client_tls_policy] = mock_rpc + + request = {} + await client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.GetClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + )) + response = await client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = client_tls_policy.GetClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, client_tls_policy.ClientTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.sni == 'sni_value' + + +@pytest.mark.asyncio +async def test_get_client_tls_policy_async_from_dict(): + await test_get_client_tls_policy_async(request_type=dict) + +def test_get_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.GetClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value = client_tls_policy.ClientTlsPolicy() + client.get_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.GetClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) + await client.get_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ClientTlsPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + client_tls_policy.GetClientTlsPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ClientTlsPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_client_tls_policy( + client_tls_policy.GetClientTlsPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_client_tls_policy.CreateClientTlsPolicyRequest, + dict, +]) +def test_create_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest( + parent='parent_value', + client_tls_policy_id='client_tls_policy_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_client_tls_policy.CreateClientTlsPolicyRequest( + parent='parent_value', + client_tls_policy_id='client_tls_policy_id_value', + ) + +def test_create_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_client_tls_policy] = mock_rpc + request = {} + client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_client_tls_policy] = mock_rpc + + request = {} + await client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_client_tls_policy_async_from_dict(): + await test_create_client_tls_policy_async(request_type=dict) + +def test_create_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_client_tls_policy( + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].client_tls_policy_id + mock_val = 'client_tls_policy_id_value' + assert arg == mock_val + + +def test_create_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + gcn_client_tls_policy.CreateClientTlsPolicyRequest(), + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + +@pytest.mark.asyncio +async def test_create_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_client_tls_policy( + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].client_tls_policy_id + mock_val = 'client_tls_policy_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_client_tls_policy( + gcn_client_tls_policy.CreateClientTlsPolicyRequest(), + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_client_tls_policy.UpdateClientTlsPolicyRequest, + dict, +]) +def test_update_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_client_tls_policy.UpdateClientTlsPolicyRequest( + ) + +def test_update_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_client_tls_policy] = mock_rpc + request = {} + client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_client_tls_policy] = mock_rpc + + request = {} + await client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_client_tls_policy_async_from_dict(): + await test_update_client_tls_policy_async(request_type=dict) + +def test_update_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + request.client_tls_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_client_tls_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', + 'client_tls_policy.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + request.client_tls_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_client_tls_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', + 'client_tls_policy.name=name_value', + ) in kw['metadata'] + + +def test_update_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_client_tls_policy( + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_client_tls_policy( + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_client_tls_policy( + gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.DeleteClientTlsPolicyRequest, + dict, +]) +def test_delete_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = client_tls_policy.DeleteClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = client_tls_policy.DeleteClientTlsPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == client_tls_policy.DeleteClientTlsPolicyRequest( + name='name_value', + ) + +def test_delete_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_client_tls_policy] = mock_rpc + request = {} + client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_client_tls_policy] = mock_rpc + + request = {} + await client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.DeleteClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = client_tls_policy.DeleteClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_async_from_dict(): + await test_delete_client_tls_policy_async(request_type=dict) + +def test_delete_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.DeleteClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.DeleteClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + client_tls_policy.DeleteClientTlsPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_client_tls_policy( + client_tls_policy.DeleteClientTlsPolicyRequest(), + name='name_value', + ) + + +def test_list_authorization_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_authorization_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_authorization_policies] = mock_rpc + + request = {} + client.list_authorization_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_authorization_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_authorization_policies_rest_required_fields(request_type=authorization_policy.ListAuthorizationPoliciesRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_authorization_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_authorization_policies._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = authorization_policy.ListAuthorizationPoliciesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = authorization_policy.ListAuthorizationPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_authorization_policies(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_authorization_policies_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_authorization_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_authorization_policies_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = authorization_policy.ListAuthorizationPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = authorization_policy.ListAuthorizationPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_authorization_policies(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/authorizationPolicies" % client.transport._host, args[1]) + + +def test_list_authorization_policies_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_authorization_policies( + authorization_policy.ListAuthorizationPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_authorization_policies_rest_pager(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='abc', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[], + next_page_token='def', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='ghi', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(authorization_policy.ListAuthorizationPoliciesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_authorization_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, authorization_policy.AuthorizationPolicy) + for i in results) + + pages = list(client.list_authorization_policies(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_authorization_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_authorization_policy] = mock_rpc + + request = {} + client.get_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_authorization_policy_rest_required_fields(request_type=authorization_policy.GetAuthorizationPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_authorization_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_authorization_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = authorization_policy.AuthorizationPolicy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = authorization_policy.AuthorizationPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_authorization_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_authorization_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_authorization_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_authorization_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = authorization_policy.AuthorizationPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = authorization_policy.AuthorizationPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_authorization_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/authorizationPolicies/*}" % client.transport._host, args[1]) + + +def test_get_authorization_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_authorization_policy( + authorization_policy.GetAuthorizationPolicyRequest(), + name='name_value', + ) + + +def test_create_authorization_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_authorization_policy] = mock_rpc + + request = {} + client.create_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_authorization_policy_rest_required_fields(request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["authorization_policy_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "authorizationPolicyId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_authorization_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "authorizationPolicyId" in jsonified_request + assert jsonified_request["authorizationPolicyId"] == request_init["authorization_policy_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["authorizationPolicyId"] = 'authorization_policy_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_authorization_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("authorization_policy_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "authorizationPolicyId" in jsonified_request + assert jsonified_request["authorizationPolicyId"] == 'authorization_policy_id_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_authorization_policy(request) + + expected_params = [ + ( + "authorizationPolicyId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_authorization_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_authorization_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("authorizationPolicyId", )) & set(("parent", "authorizationPolicyId", "authorizationPolicy", ))) + + +def test_create_authorization_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + authorization_policy_id='authorization_policy_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_authorization_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/authorizationPolicies" % client.transport._host, args[1]) + + +def test_create_authorization_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_authorization_policy( + gcn_authorization_policy.CreateAuthorizationPolicyRequest(), + parent='parent_value', + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + authorization_policy_id='authorization_policy_id_value', + ) + + +def test_update_authorization_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_authorization_policy] = mock_rpc + + request = {} + client.update_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_authorization_policy_rest_required_fields(request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_authorization_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_authorization_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_authorization_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_authorization_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_authorization_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("authorizationPolicy", ))) + + +def test_update_authorization_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'authorization_policy': {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_authorization_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{authorization_policy.name=projects/*/locations/*/authorizationPolicies/*}" % client.transport._host, args[1]) + + +def test_update_authorization_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_authorization_policy( + gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_authorization_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_authorization_policy] = mock_rpc + + request = {} + client.delete_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_authorization_policy_rest_required_fields(request_type=authorization_policy.DeleteAuthorizationPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_authorization_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_authorization_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_authorization_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_authorization_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_authorization_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_authorization_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_authorization_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/authorizationPolicies/*}" % client.transport._host, args[1]) + + +def test_delete_authorization_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_authorization_policy( + authorization_policy.DeleteAuthorizationPolicyRequest(), + name='name_value', + ) + + +def test_list_server_tls_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_server_tls_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_server_tls_policies] = mock_rpc + + request = {} + client.list_server_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_server_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_server_tls_policies_rest_required_fields(request_type=server_tls_policy.ListServerTlsPoliciesRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_server_tls_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_server_tls_policies._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = server_tls_policy.ListServerTlsPoliciesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = server_tls_policy.ListServerTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_server_tls_policies(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_server_tls_policies_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_server_tls_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_server_tls_policies_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = server_tls_policy.ListServerTlsPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = server_tls_policy.ListServerTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_server_tls_policies(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/serverTlsPolicies" % client.transport._host, args[1]) + + +def test_list_server_tls_policies_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_server_tls_policies( + server_tls_policy.ListServerTlsPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_server_tls_policies_rest_pager(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='abc', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[], + next_page_token='def', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='ghi', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(server_tls_policy.ListServerTlsPoliciesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_server_tls_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) + for i in results) + + pages = list(client.list_server_tls_policies(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_server_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_server_tls_policy] = mock_rpc + + request = {} + client.get_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_server_tls_policy_rest_required_fields(request_type=server_tls_policy.GetServerTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_server_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_server_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = server_tls_policy.ServerTlsPolicy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = server_tls_policy.ServerTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_server_tls_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_server_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_server_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_server_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = server_tls_policy.ServerTlsPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = server_tls_policy.ServerTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_server_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/serverTlsPolicies/*}" % client.transport._host, args[1]) + + +def test_get_server_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_server_tls_policy( + server_tls_policy.GetServerTlsPolicyRequest(), + name='name_value', + ) + + +def test_create_server_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_server_tls_policy] = mock_rpc + + request = {} + client.create_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_server_tls_policy_rest_required_fields(request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["server_tls_policy_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "serverTlsPolicyId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_server_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "serverTlsPolicyId" in jsonified_request + assert jsonified_request["serverTlsPolicyId"] == request_init["server_tls_policy_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["serverTlsPolicyId"] = 'server_tls_policy_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_server_tls_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("server_tls_policy_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "serverTlsPolicyId" in jsonified_request + assert jsonified_request["serverTlsPolicyId"] == 'server_tls_policy_id_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_server_tls_policy(request) + + expected_params = [ + ( + "serverTlsPolicyId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_server_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_server_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("serverTlsPolicyId", )) & set(("parent", "serverTlsPolicyId", "serverTlsPolicy", ))) + + +def test_create_server_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + server_tls_policy_id='server_tls_policy_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_server_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/serverTlsPolicies" % client.transport._host, args[1]) + + +def test_create_server_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_server_tls_policy( + gcn_server_tls_policy.CreateServerTlsPolicyRequest(), + parent='parent_value', + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + server_tls_policy_id='server_tls_policy_id_value', + ) + + +def test_update_server_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_server_tls_policy] = mock_rpc + + request = {} + client.update_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_server_tls_policy_rest_required_fields(request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_server_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_server_tls_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_server_tls_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_server_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_server_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("serverTlsPolicy", ))) + + +def test_update_server_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'server_tls_policy': {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_server_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{server_tls_policy.name=projects/*/locations/*/serverTlsPolicies/*}" % client.transport._host, args[1]) + + +def test_update_server_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_server_tls_policy( + gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_server_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_server_tls_policy] = mock_rpc + + request = {} + client.delete_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_server_tls_policy_rest_required_fields(request_type=server_tls_policy.DeleteServerTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_server_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_server_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_server_tls_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_server_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_server_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_server_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_server_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/serverTlsPolicies/*}" % client.transport._host, args[1]) + + +def test_delete_server_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_server_tls_policy( + server_tls_policy.DeleteServerTlsPolicyRequest(), + name='name_value', + ) + + +def test_list_client_tls_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_client_tls_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_client_tls_policies] = mock_rpc + + request = {} + client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_client_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_client_tls_policies_rest_required_fields(request_type=client_tls_policy.ListClientTlsPoliciesRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_client_tls_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_client_tls_policies._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ListClientTlsPoliciesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_client_tls_policies(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_client_tls_policies_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_client_tls_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_client_tls_policies_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ListClientTlsPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_client_tls_policies(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/clientTlsPolicies" % client.transport._host, args[1]) + + +def test_list_client_tls_policies_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_client_tls_policies( + client_tls_policy.ListClientTlsPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_client_tls_policies_rest_pager(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(client_tls_policy.ListClientTlsPoliciesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_client_tls_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) + for i in results) + + pages = list(client.list_client_tls_policies(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_client_tls_policy] = mock_rpc + + request = {} + client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_client_tls_policy_rest_required_fields(request_type=client_tls_policy.GetClientTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ClientTlsPolicy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_client_tls_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ClientTlsPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_client_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) + + +def test_get_client_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_client_tls_policy( + client_tls_policy.GetClientTlsPolicyRequest(), + name='name_value', + ) + + +def test_create_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_client_tls_policy] = mock_rpc + + request = {} + client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_client_tls_policy_rest_required_fields(request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["client_tls_policy_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "clientTlsPolicyId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clientTlsPolicyId" in jsonified_request + assert jsonified_request["clientTlsPolicyId"] == request_init["client_tls_policy_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clientTlsPolicyId"] = 'client_tls_policy_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_client_tls_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("client_tls_policy_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "clientTlsPolicyId" in jsonified_request + assert jsonified_request["clientTlsPolicyId"] == 'client_tls_policy_id_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_client_tls_policy(request) + + expected_params = [ + ( + "clientTlsPolicyId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("clientTlsPolicyId", )) & set(("parent", "clientTlsPolicyId", "clientTlsPolicy", ))) + + +def test_create_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_client_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/clientTlsPolicies" % client.transport._host, args[1]) + + +def test_create_client_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_client_tls_policy( + gcn_client_tls_policy.CreateClientTlsPolicyRequest(), + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + +def test_update_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_client_tls_policy] = mock_rpc + + request = {} + client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_client_tls_policy_rest_required_fields(request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_client_tls_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_client_tls_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("clientTlsPolicy", ))) + + +def test_update_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_client_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) + + +def test_update_client_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_client_tls_policy( + gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_client_tls_policy] = mock_rpc + + request = {} + client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_client_tls_policy_rest_required_fields(request_type=client_tls_policy.DeleteClientTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_client_tls_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_client_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) + + +def test_delete_client_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_client_tls_policy( + client_tls_policy.DeleteClientTlsPolicyRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = NetworkSecurityClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.NetworkSecurityGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.NetworkSecurityGrpcTransport, + transports.NetworkSecurityGrpcAsyncIOTransport, + transports.NetworkSecurityRestTransport, +]) +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_kind_grpc(): + transport = NetworkSecurityClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_authorization_policies_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + client.list_authorization_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.ListAuthorizationPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + call.return_value = authorization_policy.AuthorizationPolicy() + client.get_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.GetAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_server_tls_policies_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + client.list_server_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.ListServerTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + call.return_value = server_tls_policy.ServerTlsPolicy() + client.get_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.GetServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_client_tls_policies_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + client.list_client_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.ListClientTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value = client_tls_policy.ClientTlsPolicy() + client.get_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.GetClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = NetworkSecurityAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_authorization_policies_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse( + next_page_token='next_page_token_value', + )) + await client.list_authorization_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.ListAuthorizationPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy( + name='name_value', + description='description_value', + action=authorization_policy.AuthorizationPolicy.Action.ALLOW, + )) + await client.get_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.GetAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_server_tls_policies_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse( + next_page_token='next_page_token_value', + )) + await client.list_server_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.ListServerTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy( + name='name_value', + description='description_value', + allow_open=True, + )) + await client.get_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.GetServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_client_tls_policies_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + )) + await client.list_client_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.ListClientTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + )) + await client.get_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.GetClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = NetworkSecurityClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_authorization_policies_rest_bad_request(request_type=authorization_policy.ListAuthorizationPoliciesRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_authorization_policies(request) + + +@pytest.mark.parametrize("request_type", [ + authorization_policy.ListAuthorizationPoliciesRequest, + dict, +]) +def test_list_authorization_policies_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = authorization_policy.ListAuthorizationPoliciesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = authorization_policy.ListAuthorizationPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_authorization_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthorizationPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_authorization_policies_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_authorization_policies") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_authorization_policies_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_list_authorization_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = authorization_policy.ListAuthorizationPoliciesRequest.pb(authorization_policy.ListAuthorizationPoliciesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = authorization_policy.ListAuthorizationPoliciesResponse.to_json(authorization_policy.ListAuthorizationPoliciesResponse()) + req.return_value.content = return_value + + request = authorization_policy.ListAuthorizationPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + post_with_metadata.return_value = authorization_policy.ListAuthorizationPoliciesResponse(), metadata + + client.list_authorization_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_authorization_policy_rest_bad_request(request_type=authorization_policy.GetAuthorizationPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_authorization_policy(request) + + +@pytest.mark.parametrize("request_type", [ + authorization_policy.GetAuthorizationPolicyRequest, + dict, +]) +def test_get_authorization_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = authorization_policy.AuthorizationPolicy( + name='name_value', + description='description_value', + action=authorization_policy.AuthorizationPolicy.Action.ALLOW, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = authorization_policy.AuthorizationPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_authorization_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, authorization_policy.AuthorizationPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_authorization_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_authorization_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_authorization_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_get_authorization_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = authorization_policy.GetAuthorizationPolicyRequest.pb(authorization_policy.GetAuthorizationPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = authorization_policy.AuthorizationPolicy.to_json(authorization_policy.AuthorizationPolicy()) + req.return_value.content = return_value + + request = authorization_policy.GetAuthorizationPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = authorization_policy.AuthorizationPolicy() + post_with_metadata.return_value = authorization_policy.AuthorizationPolicy(), metadata + + client.get_authorization_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_authorization_policy_rest_bad_request(request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_authorization_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_authorization_policy.CreateAuthorizationPolicyRequest, + dict, +]) +def test_create_authorization_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["authorization_policy"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'action': 1, 'rules': [{'sources': [{'principals': ['principals_value1', 'principals_value2'], 'ip_blocks': ['ip_blocks_value1', 'ip_blocks_value2']}], 'destinations': [{'hosts': ['hosts_value1', 'hosts_value2'], 'ports': [569, 570], 'methods': ['methods_value1', 'methods_value2'], 'http_header_match': {'regex_match': 'regex_match_value', 'header_name': 'header_name_value'}}]}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_authorization_policy.CreateAuthorizationPolicyRequest.meta.fields["authorization_policy"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["authorization_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["authorization_policy"][field])): + del request_init["authorization_policy"][field][i][subfield] + else: + del request_init["authorization_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_authorization_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_authorization_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_authorization_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_authorization_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_create_authorization_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_authorization_policy.CreateAuthorizationPolicyRequest.pb(gcn_authorization_policy.CreateAuthorizationPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_authorization_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_authorization_policy_rest_bad_request(request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'authorization_policy': {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_authorization_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_authorization_policy.UpdateAuthorizationPolicyRequest, + dict, +]) +def test_update_authorization_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'authorization_policy': {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}} + request_init["authorization_policy"] = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'action': 1, 'rules': [{'sources': [{'principals': ['principals_value1', 'principals_value2'], 'ip_blocks': ['ip_blocks_value1', 'ip_blocks_value2']}], 'destinations': [{'hosts': ['hosts_value1', 'hosts_value2'], 'ports': [569, 570], 'methods': ['methods_value1', 'methods_value2'], 'http_header_match': {'regex_match': 'regex_match_value', 'header_name': 'header_name_value'}}]}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.meta.fields["authorization_policy"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["authorization_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["authorization_policy"][field])): + del request_init["authorization_policy"][field][i][subfield] + else: + del request_init["authorization_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_authorization_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_authorization_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_authorization_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_authorization_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_update_authorization_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.pb(gcn_authorization_policy.UpdateAuthorizationPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_authorization_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_authorization_policy_rest_bad_request(request_type=authorization_policy.DeleteAuthorizationPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_authorization_policy(request) + + +@pytest.mark.parametrize("request_type", [ + authorization_policy.DeleteAuthorizationPolicyRequest, + dict, +]) +def test_delete_authorization_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_authorization_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_authorization_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_authorization_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_authorization_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_delete_authorization_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = authorization_policy.DeleteAuthorizationPolicyRequest.pb(authorization_policy.DeleteAuthorizationPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = authorization_policy.DeleteAuthorizationPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_authorization_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_server_tls_policies_rest_bad_request(request_type=server_tls_policy.ListServerTlsPoliciesRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_server_tls_policies(request) + + +@pytest.mark.parametrize("request_type", [ + server_tls_policy.ListServerTlsPoliciesRequest, + dict, +]) +def test_list_server_tls_policies_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = server_tls_policy.ListServerTlsPoliciesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = server_tls_policy.ListServerTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_server_tls_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServerTlsPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_server_tls_policies_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_server_tls_policies") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_server_tls_policies_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_list_server_tls_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = server_tls_policy.ListServerTlsPoliciesRequest.pb(server_tls_policy.ListServerTlsPoliciesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = server_tls_policy.ListServerTlsPoliciesResponse.to_json(server_tls_policy.ListServerTlsPoliciesResponse()) + req.return_value.content = return_value + + request = server_tls_policy.ListServerTlsPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + post_with_metadata.return_value = server_tls_policy.ListServerTlsPoliciesResponse(), metadata + + client.list_server_tls_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_server_tls_policy_rest_bad_request(request_type=server_tls_policy.GetServerTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_server_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + server_tls_policy.GetServerTlsPolicyRequest, + dict, +]) +def test_get_server_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = server_tls_policy.ServerTlsPolicy( + name='name_value', + description='description_value', + allow_open=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = server_tls_policy.ServerTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_server_tls_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, server_tls_policy.ServerTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.allow_open is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_server_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_server_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_server_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_get_server_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = server_tls_policy.GetServerTlsPolicyRequest.pb(server_tls_policy.GetServerTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = server_tls_policy.ServerTlsPolicy.to_json(server_tls_policy.ServerTlsPolicy()) + req.return_value.content = return_value + + request = server_tls_policy.GetServerTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = server_tls_policy.ServerTlsPolicy() + post_with_metadata.return_value = server_tls_policy.ServerTlsPolicy(), metadata + + client.get_server_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_server_tls_policy_rest_bad_request(request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_server_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_server_tls_policy.CreateServerTlsPolicyRequest, + dict, +]) +def test_create_server_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["server_tls_policy"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'allow_open': True, 'server_certificate': {'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'mtls_policy': {'client_validation_ca': [{'grpc_endpoint': {}, 'certificate_provider_instance': {}}]}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_server_tls_policy.CreateServerTlsPolicyRequest.meta.fields["server_tls_policy"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["server_tls_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["server_tls_policy"][field])): + del request_init["server_tls_policy"][field][i][subfield] + else: + del request_init["server_tls_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_server_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_server_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_server_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_server_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_create_server_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_server_tls_policy.CreateServerTlsPolicyRequest.pb(gcn_server_tls_policy.CreateServerTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_server_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_server_tls_policy_rest_bad_request(request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'server_tls_policy': {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_server_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_server_tls_policy.UpdateServerTlsPolicyRequest, + dict, +]) +def test_update_server_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'server_tls_policy': {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'}} + request_init["server_tls_policy"] = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'allow_open': True, 'server_certificate': {'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'mtls_policy': {'client_validation_ca': [{'grpc_endpoint': {}, 'certificate_provider_instance': {}}]}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.meta.fields["server_tls_policy"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["server_tls_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["server_tls_policy"][field])): + del request_init["server_tls_policy"][field][i][subfield] + else: + del request_init["server_tls_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_server_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_server_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_server_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_server_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_update_server_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.pb(gcn_server_tls_policy.UpdateServerTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_server_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_server_tls_policy_rest_bad_request(request_type=server_tls_policy.DeleteServerTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_server_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + server_tls_policy.DeleteServerTlsPolicyRequest, + dict, +]) +def test_delete_server_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_server_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_server_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_server_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_server_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_delete_server_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = server_tls_policy.DeleteServerTlsPolicyRequest.pb(server_tls_policy.DeleteServerTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = server_tls_policy.DeleteServerTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_server_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_client_tls_policies_rest_bad_request(request_type=client_tls_policy.ListClientTlsPoliciesRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_client_tls_policies(request) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.ListClientTlsPoliciesRequest, + dict, +]) +def test_list_client_tls_policies_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_client_tls_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClientTlsPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_client_tls_policies_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_client_tls_policies") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_client_tls_policies_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_list_client_tls_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = client_tls_policy.ListClientTlsPoliciesRequest.pb(client_tls_policy.ListClientTlsPoliciesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = client_tls_policy.ListClientTlsPoliciesResponse.to_json(client_tls_policy.ListClientTlsPoliciesResponse()) + req.return_value.content = return_value + + request = client_tls_policy.ListClientTlsPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + post_with_metadata.return_value = client_tls_policy.ListClientTlsPoliciesResponse(), metadata + + client.list_client_tls_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_client_tls_policy_rest_bad_request(request_type=client_tls_policy.GetClientTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_client_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.GetClientTlsPolicyRequest, + dict, +]) +def test_get_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_client_tls_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, client_tls_policy.ClientTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.sni == 'sni_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_client_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_client_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_get_client_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = client_tls_policy.GetClientTlsPolicyRequest.pb(client_tls_policy.GetClientTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = client_tls_policy.ClientTlsPolicy.to_json(client_tls_policy.ClientTlsPolicy()) + req.return_value.content = return_value + + request = client_tls_policy.GetClientTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = client_tls_policy.ClientTlsPolicy() + post_with_metadata.return_value = client_tls_policy.ClientTlsPolicy(), metadata + + client.get_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_client_tls_policy_rest_bad_request(request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_client_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_client_tls_policy.CreateClientTlsPolicyRequest, + dict, +]) +def test_create_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["client_tls_policy"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'sni': 'sni_value', 'client_certificate': {'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'server_validation_ca': [{'grpc_endpoint': {}, 'certificate_provider_instance': {}}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_client_tls_policy.CreateClientTlsPolicyRequest.meta.fields["client_tls_policy"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["client_tls_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["client_tls_policy"][field])): + del request_init["client_tls_policy"][field][i][subfield] + else: + del request_init["client_tls_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_client_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_client_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_client_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_create_client_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(gcn_client_tls_policy.CreateClientTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_client_tls_policy_rest_bad_request(request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_client_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_client_tls_policy.UpdateClientTlsPolicyRequest, + dict, +]) +def test_update_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} + request_init["client_tls_policy"] = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'sni': 'sni_value', 'client_certificate': {'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'server_validation_ca': [{'grpc_endpoint': {}, 'certificate_provider_instance': {}}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.meta.fields["client_tls_policy"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["client_tls_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["client_tls_policy"][field])): + del request_init["client_tls_policy"][field][i][subfield] + else: + del request_init["client_tls_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_client_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_client_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_client_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_update_client_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(gcn_client_tls_policy.UpdateClientTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_client_tls_policy_rest_bad_request(request_type=client_tls_policy.DeleteClientTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_client_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.DeleteClientTlsPolicyRequest, + dict, +]) +def test_delete_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_client_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_client_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_client_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_delete_client_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = client_tls_policy.DeleteClientTlsPolicyRequest.pb(client_tls_policy.DeleteClientTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = client_tls_policy.DeleteClientTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_initialize_client_w_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_authorization_policies_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + client.list_authorization_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.ListAuthorizationPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_authorization_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + client.get_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.GetAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_authorization_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + client.create_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_authorization_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + client.update_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_authorization_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + client.delete_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_server_tls_policies_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + client.list_server_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.ListServerTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_server_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + client.get_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.GetServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_server_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + client.create_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_server_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + client.update_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_server_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + client.delete_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_client_tls_policies_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + client.list_client_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.ListClientTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + client.get_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.GetClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + client.create_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + client.update_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + client.delete_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() + + assert args[0] == request_msg + + +def test_network_security_rest_lro_client(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, +operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.NetworkSecurityGrpcTransport, + ) + +def test_network_security_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.NetworkSecurityTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_network_security_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.network_security_v1.services.network_security.transports.NetworkSecurityTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.NetworkSecurityTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_authorization_policies', + 'get_authorization_policy', + 'create_authorization_policy', + 'update_authorization_policy', + 'delete_authorization_policy', + 'list_server_tls_policies', + 'get_server_tls_policy', + 'create_server_tls_policy', + 'update_server_tls_policy', + 'delete_server_tls_policy', + 'list_client_tls_policies', + 'get_client_tls_policy', + 'create_client_tls_policy', + 'update_client_tls_policy', + 'delete_client_tls_policy', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_network_security_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.network_security_v1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkSecurityTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_network_security_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.network_security_v1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkSecurityTransport() + adc.assert_called_once() + + +def test_network_security_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) + NetworkSecurityClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkSecurityGrpcTransport, + transports.NetworkSecurityGrpcAsyncIOTransport, + ], +) +def test_network_security_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.NetworkSecurityGrpcTransport, + transports.NetworkSecurityGrpcAsyncIOTransport, + transports.NetworkSecurityRestTransport, + ], +) +def test_network_security_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.NetworkSecurityGrpcTransport, grpc_helpers), + (transports.NetworkSecurityGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_network_security_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( + "networksecurity.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="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) +def test_network_security_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_network_security_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.NetworkSecurityRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_network_security_host_no_port(transport_name): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networksecurity.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_network_security_host_with_port(transport_name): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networksecurity.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networksecurity.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_network_security_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = NetworkSecurityClient( + credentials=creds1, + transport=transport_name, + ) + client2 = NetworkSecurityClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_authorization_policies._session + session2 = client2.transport.list_authorization_policies._session + assert session1 != session2 + session1 = client1.transport.get_authorization_policy._session + session2 = client2.transport.get_authorization_policy._session + assert session1 != session2 + session1 = client1.transport.create_authorization_policy._session + session2 = client2.transport.create_authorization_policy._session + assert session1 != session2 + session1 = client1.transport.update_authorization_policy._session + session2 = client2.transport.update_authorization_policy._session + assert session1 != session2 + session1 = client1.transport.delete_authorization_policy._session + session2 = client2.transport.delete_authorization_policy._session + assert session1 != session2 + session1 = client1.transport.list_server_tls_policies._session + session2 = client2.transport.list_server_tls_policies._session + assert session1 != session2 + session1 = client1.transport.get_server_tls_policy._session + session2 = client2.transport.get_server_tls_policy._session + assert session1 != session2 + session1 = client1.transport.create_server_tls_policy._session + session2 = client2.transport.create_server_tls_policy._session + assert session1 != session2 + session1 = client1.transport.update_server_tls_policy._session + session2 = client2.transport.update_server_tls_policy._session + assert session1 != session2 + session1 = client1.transport.delete_server_tls_policy._session + session2 = client2.transport.delete_server_tls_policy._session + assert session1 != session2 + session1 = client1.transport.list_client_tls_policies._session + session2 = client2.transport.list_client_tls_policies._session + assert session1 != session2 + session1 = client1.transport.get_client_tls_policy._session + session2 = client2.transport.get_client_tls_policy._session + assert session1 != session2 + session1 = client1.transport.create_client_tls_policy._session + session2 = client2.transport.create_client_tls_policy._session + assert session1 != session2 + session1 = client1.transport.update_client_tls_policy._session + session2 = client2.transport.update_client_tls_policy._session + assert session1 != session2 + session1 = client1.transport.delete_client_tls_policy._session + session2 = client2.transport.delete_client_tls_policy._session + assert session1 != session2 +def test_network_security_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NetworkSecurityGrpcTransport( + 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_network_security_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NetworkSecurityGrpcAsyncIOTransport( + 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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) +def test_network_security_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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) +def test_network_security_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_network_security_grpc_lro_client(): + client = NetworkSecurityClient( + 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_network_security_grpc_lro_async_client(): + client = NetworkSecurityAsyncClient( + 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_authorization_policy_path(): + project = "squid" + location = "clam" + authorization_policy = "whelk" + expected = "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format(project=project, location=location, authorization_policy=authorization_policy, ) + actual = NetworkSecurityClient.authorization_policy_path(project, location, authorization_policy) + assert expected == actual + + +def test_parse_authorization_policy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "authorization_policy": "nudibranch", + } + path = NetworkSecurityClient.authorization_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_authorization_policy_path(path) + assert expected == actual + +def test_client_tls_policy_path(): + project = "cuttlefish" + location = "mussel" + client_tls_policy = "winkle" + expected = "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) + actual = NetworkSecurityClient.client_tls_policy_path(project, location, client_tls_policy) + assert expected == actual + + +def test_parse_client_tls_policy_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "client_tls_policy": "abalone", + } + path = NetworkSecurityClient.client_tls_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_client_tls_policy_path(path) + assert expected == actual + +def test_server_tls_policy_path(): + project = "squid" + location = "clam" + server_tls_policy = "whelk" + expected = "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format(project=project, location=location, server_tls_policy=server_tls_policy, ) + actual = NetworkSecurityClient.server_tls_policy_path(project, location, server_tls_policy) + assert expected == actual + + +def test_parse_server_tls_policy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "server_tls_policy": "nudibranch", + } + path = NetworkSecurityClient.server_tls_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_server_tls_policy_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = NetworkSecurityClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = NetworkSecurityClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = NetworkSecurityClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = NetworkSecurityClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = NetworkSecurityClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = NetworkSecurityClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = NetworkSecurityClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = NetworkSecurityClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = NetworkSecurityClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = NetworkSecurityClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: + transport_class = NetworkSecurityClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py new file mode 100644 index 000000000000..7e2d259d528d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py @@ -0,0 +1,10025 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.network_security_v1.services.organization_address_group_service import OrganizationAddressGroupServiceAsyncClient +from google.cloud.network_security_v1.services.organization_address_group_service import OrganizationAddressGroupServiceClient +from google.cloud.network_security_v1.services.organization_address_group_service import pagers +from google.cloud.network_security_v1.services.organization_address_group_service import transports +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import common +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# 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 + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(None) is None + assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert OrganizationAddressGroupServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + OrganizationAddressGroupServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + OrganizationAddressGroupServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert OrganizationAddressGroupServiceClient._get_client_cert_source(None, False) is None + assert OrganizationAddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert OrganizationAddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert OrganizationAddressGroupServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert OrganizationAddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(OrganizationAddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceClient)) +@mock.patch.object(OrganizationAddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE + default_endpoint = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert OrganizationAddressGroupServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "always") == OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + OrganizationAddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert OrganizationAddressGroupServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert OrganizationAddressGroupServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert OrganizationAddressGroupServiceClient._get_universe_domain(None, None) == OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + OrganizationAddressGroupServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = OrganizationAddressGroupServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = OrganizationAddressGroupServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (OrganizationAddressGroupServiceClient, "grpc"), + (OrganizationAddressGroupServiceAsyncClient, "grpc_asyncio"), + (OrganizationAddressGroupServiceClient, "rest"), +]) +def test_organization_address_group_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networksecurity.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.OrganizationAddressGroupServiceGrpcTransport, "grpc"), + (transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.OrganizationAddressGroupServiceRestTransport, "rest"), +]) +def test_organization_address_group_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (OrganizationAddressGroupServiceClient, "grpc"), + (OrganizationAddressGroupServiceAsyncClient, "grpc_asyncio"), + (OrganizationAddressGroupServiceClient, "rest"), +]) +def test_organization_address_group_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networksecurity.googleapis.com' + ) + + +def test_organization_address_group_service_client_get_transport_class(): + transport = OrganizationAddressGroupServiceClient.get_transport_class() + available_transports = [ + transports.OrganizationAddressGroupServiceGrpcTransport, + transports.OrganizationAddressGroupServiceRestTransport, + ] + assert transport in available_transports + + transport = OrganizationAddressGroupServiceClient.get_transport_class("grpc") + assert transport == transports.OrganizationAddressGroupServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc"), + (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceRestTransport, "rest"), +]) +@mock.patch.object(OrganizationAddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceClient)) +@mock.patch.object(OrganizationAddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient)) +def test_organization_address_group_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(OrganizationAddressGroupServiceClient, '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(OrganizationAddressGroupServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc", "true"), + (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc", "false"), + (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceRestTransport, "rest", "true"), + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(OrganizationAddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceClient)) +@mock.patch.object(OrganizationAddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_organization_address_group_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + OrganizationAddressGroupServiceClient, OrganizationAddressGroupServiceAsyncClient +]) +@mock.patch.object(OrganizationAddressGroupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationAddressGroupServiceClient)) +@mock.patch.object(OrganizationAddressGroupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationAddressGroupServiceAsyncClient)) +def test_organization_address_group_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + OrganizationAddressGroupServiceClient, OrganizationAddressGroupServiceAsyncClient +]) +@mock.patch.object(OrganizationAddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceClient)) +@mock.patch.object(OrganizationAddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient)) +def test_organization_address_group_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE + default_endpoint = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc"), + (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceRestTransport, "rest"), +]) +def test_organization_address_group_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc", grpc_helpers), + (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceRestTransport, "rest", None), +]) +def test_organization_address_group_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_organization_address_group_service_client_client_options_from_dict(): + with mock.patch('google.cloud.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = OrganizationAddressGroupServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc", grpc_helpers), + (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_organization_address_group_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networksecurity.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + address_group.ListAddressGroupsRequest, + dict, +]) +def test_list_address_groups(request_type, transport: str = 'grpc'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.ListAddressGroupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = address_group.ListAddressGroupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_address_groups_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = address_group.ListAddressGroupsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_address_groups(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == address_group.ListAddressGroupsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_address_groups_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_address_groups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_address_groups] = mock_rpc + request = {} + client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_address_groups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_address_groups_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_address_groups in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_address_groups] = mock_rpc + + request = {} + await client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_address_groups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_address_groups_async(transport: str = 'grpc_asyncio', request_type=address_group.ListAddressGroupsRequest): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = address_group.ListAddressGroupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_address_groups_async_from_dict(): + await test_list_address_groups_async(request_type=dict) + +def test_list_address_groups_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.ListAddressGroupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + call.return_value = address_group.ListAddressGroupsResponse() + client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_address_groups_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.ListAddressGroupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse()) + await client.list_address_groups(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_address_groups_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.ListAddressGroupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_address_groups( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_address_groups_flattened_error(): + client = OrganizationAddressGroupServiceClient( + 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_address_groups( + address_group.ListAddressGroupsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_address_groups_flattened_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.ListAddressGroupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_address_groups( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_address_groups_flattened_error_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_address_groups( + address_group.ListAddressGroupsRequest(), + parent='parent_value', + ) + + +def test_list_address_groups_pager(transport_name: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + next_page_token='abc', + ), + address_group.ListAddressGroupsResponse( + address_groups=[], + next_page_token='def', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + ], + next_page_token='ghi', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_address_groups(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, address_group.AddressGroup) + for i in results) +def test_list_address_groups_pages(transport_name: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + next_page_token='abc', + ), + address_group.ListAddressGroupsResponse( + address_groups=[], + next_page_token='def', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + ], + next_page_token='ghi', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_address_groups(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_address_groups_async_pager(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + next_page_token='abc', + ), + address_group.ListAddressGroupsResponse( + address_groups=[], + next_page_token='def', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + ], + next_page_token='ghi', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_address_groups(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, address_group.AddressGroup) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_address_groups_async_pages(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + next_page_token='abc', + ), + address_group.ListAddressGroupsResponse( + address_groups=[], + next_page_token='def', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + ], + next_page_token='ghi', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_address_groups(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + address_group.GetAddressGroupRequest, + dict, +]) +def test_get_address_group(request_type, transport: str = 'grpc'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.AddressGroup( + name='name_value', + description='description_value', + type_=address_group.AddressGroup.Type.IPV4, + items=['items_value'], + capacity=846, + self_link='self_link_value', + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + ) + response = client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = address_group.GetAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, address_group.AddressGroup) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.type_ == address_group.AddressGroup.Type.IPV4 + assert response.items == ['items_value'] + assert response.capacity == 846 + assert response.self_link == 'self_link_value' + assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] + + +def test_get_address_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = address_group.GetAddressGroupRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_address_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == address_group.GetAddressGroupRequest( + name='name_value', + ) + +def test_get_address_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_address_group] = mock_rpc + request = {} + client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_address_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_address_group] = mock_rpc + + request = {} + await client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_address_group_async(transport: str = 'grpc_asyncio', request_type=address_group.GetAddressGroupRequest): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup( + name='name_value', + description='description_value', + type_=address_group.AddressGroup.Type.IPV4, + items=['items_value'], + capacity=846, + self_link='self_link_value', + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + )) + response = await client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = address_group.GetAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, address_group.AddressGroup) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.type_ == address_group.AddressGroup.Type.IPV4 + assert response.items == ['items_value'] + assert response.capacity == 846 + assert response.self_link == 'self_link_value' + assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] + + +@pytest.mark.asyncio +async def test_get_address_group_async_from_dict(): + await test_get_address_group_async(request_type=dict) + +def test_get_address_group_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.GetAddressGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + call.return_value = address_group.AddressGroup() + client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_address_group_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.GetAddressGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup()) + await client.get_address_group(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_address_group_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.AddressGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_address_group( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_address_group_flattened_error(): + client = OrganizationAddressGroupServiceClient( + 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_address_group( + address_group.GetAddressGroupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_address_group_flattened_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = address_group.AddressGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_address_group( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_address_group_flattened_error_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_address_group( + address_group.GetAddressGroupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.CreateAddressGroupRequest, + dict, +]) +def test_create_address_group(request_type, transport: str = 'grpc'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.CreateAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_address_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.CreateAddressGroupRequest( + parent='parent_value', + address_group_id='address_group_id_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_address_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.CreateAddressGroupRequest( + parent='parent_value', + address_group_id='address_group_id_value', + request_id='request_id_value', + ) + +def test_create_address_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_address_group] = mock_rpc + request = {} + client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_address_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_address_group] = mock_rpc + + request = {} + await client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_address_group_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.CreateAddressGroupRequest): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.CreateAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_address_group_async_from_dict(): + await test_create_address_group_async(request_type=dict) + +def test_create_address_group_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.CreateAddressGroupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_address_group_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.CreateAddressGroupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_address_group(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_address_group_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_address_group( + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].address_group + mock_val = gcn_address_group.AddressGroup(name='name_value') + assert arg == mock_val + arg = args[0].address_group_id + mock_val = 'address_group_id_value' + assert arg == mock_val + + +def test_create_address_group_flattened_error(): + client = OrganizationAddressGroupServiceClient( + 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_address_group( + gcn_address_group.CreateAddressGroupRequest(), + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + +@pytest.mark.asyncio +async def test_create_address_group_flattened_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_address_group( + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].address_group + mock_val = gcn_address_group.AddressGroup(name='name_value') + assert arg == mock_val + arg = args[0].address_group_id + mock_val = 'address_group_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_address_group_flattened_error_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_address_group( + gcn_address_group.CreateAddressGroupRequest(), + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.UpdateAddressGroupRequest, + dict, +]) +def test_update_address_group(request_type, transport: str = 'grpc'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.UpdateAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_address_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.UpdateAddressGroupRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_address_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.UpdateAddressGroupRequest( + request_id='request_id_value', + ) + +def test_update_address_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_address_group] = mock_rpc + request = {} + client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_address_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_address_group] = mock_rpc + + request = {} + await client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_address_group_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.UpdateAddressGroupRequest): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.UpdateAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_address_group_async_from_dict(): + await test_update_address_group_async(request_type=dict) + +def test_update_address_group_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.UpdateAddressGroupRequest() + + request.address_group.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'address_group.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_address_group_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.UpdateAddressGroupRequest() + + request.address_group.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_address_group(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', + 'address_group.name=name_value', + ) in kw['metadata'] + + +def test_update_address_group_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_address_group( + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = gcn_address_group.AddressGroup(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_address_group_flattened_error(): + client = OrganizationAddressGroupServiceClient( + 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_address_group( + gcn_address_group.UpdateAddressGroupRequest(), + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_address_group_flattened_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_address_group( + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = gcn_address_group.AddressGroup(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_address_group_flattened_error_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_address_group( + gcn_address_group.UpdateAddressGroupRequest(), + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.AddAddressGroupItemsRequest, + dict, +]) +def test_add_address_group_items(request_type, transport: str = 'grpc'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.AddAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_address_group_items_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.AddAddressGroupItemsRequest( + address_group='address_group_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.add_address_group_items(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.AddAddressGroupItemsRequest( + address_group='address_group_value', + request_id='request_id_value', + ) + +def test_add_address_group_items_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_address_group_items] = mock_rpc + request = {} + client.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_add_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.add_address_group_items in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.add_address_group_items] = mock_rpc + + request = {} + await client.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.add_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_add_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.AddAddressGroupItemsRequest): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__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.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.AddAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_add_address_group_items_async_from_dict(): + await test_add_address_group_items_async(request_type=dict) + +def test_add_address_group_items_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.AddAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'address_group=address_group_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_add_address_group_items_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.AddAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.add_address_group_items(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', + 'address_group=address_group_value', + ) in kw['metadata'] + + +def test_add_address_group_items_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_address_group_items( + address_group='address_group_value', + items=['items_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].items + mock_val = ['items_value'] + assert arg == mock_val + + +def test_add_address_group_items_flattened_error(): + client = OrganizationAddressGroupServiceClient( + 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.add_address_group_items( + gcn_address_group.AddAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + +@pytest.mark.asyncio +async def test_add_address_group_items_flattened_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_address_group_items( + address_group='address_group_value', + items=['items_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].items + mock_val = ['items_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_add_address_group_items_flattened_error_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_address_group_items( + gcn_address_group.AddAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.RemoveAddressGroupItemsRequest, + dict, +]) +def test_remove_address_group_items(request_type, transport: str = 'grpc'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.RemoveAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_remove_address_group_items_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.RemoveAddressGroupItemsRequest( + address_group='address_group_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.remove_address_group_items(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.RemoveAddressGroupItemsRequest( + address_group='address_group_value', + request_id='request_id_value', + ) + +def test_remove_address_group_items_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_address_group_items] = mock_rpc + request = {} + client.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.remove_address_group_items in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.remove_address_group_items] = mock_rpc + + request = {} + await client.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.remove_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_remove_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.RemoveAddressGroupItemsRequest): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__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.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.RemoveAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_remove_address_group_items_async_from_dict(): + await test_remove_address_group_items_async(request_type=dict) + +def test_remove_address_group_items_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.RemoveAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'address_group=address_group_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_remove_address_group_items_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.RemoveAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.remove_address_group_items(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', + 'address_group=address_group_value', + ) in kw['metadata'] + + +def test_remove_address_group_items_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_address_group_items( + address_group='address_group_value', + items=['items_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].items + mock_val = ['items_value'] + assert arg == mock_val + + +def test_remove_address_group_items_flattened_error(): + client = OrganizationAddressGroupServiceClient( + 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.remove_address_group_items( + gcn_address_group.RemoveAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + +@pytest.mark.asyncio +async def test_remove_address_group_items_flattened_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_address_group_items( + address_group='address_group_value', + items=['items_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].items + mock_val = ['items_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_remove_address_group_items_flattened_error_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_address_group_items( + gcn_address_group.RemoveAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.CloneAddressGroupItemsRequest, + dict, +]) +def test_clone_address_group_items(request_type, transport: str = 'grpc'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.CloneAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_clone_address_group_items_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.CloneAddressGroupItemsRequest( + address_group='address_group_value', + source_address_group='source_address_group_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.clone_address_group_items(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.CloneAddressGroupItemsRequest( + address_group='address_group_value', + source_address_group='source_address_group_value', + request_id='request_id_value', + ) + +def test_clone_address_group_items_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.clone_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.clone_address_group_items] = mock_rpc + request = {} + client.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.clone_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_clone_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.clone_address_group_items in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.clone_address_group_items] = mock_rpc + + request = {} + await client.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.clone_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_clone_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.CloneAddressGroupItemsRequest): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__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.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.CloneAddressGroupItemsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_clone_address_group_items_async_from_dict(): + await test_clone_address_group_items_async(request_type=dict) + +def test_clone_address_group_items_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.CloneAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'address_group=address_group_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_clone_address_group_items_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.CloneAddressGroupItemsRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.clone_address_group_items(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', + 'address_group=address_group_value', + ) in kw['metadata'] + + +def test_clone_address_group_items_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.clone_address_group_items( + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].source_address_group + mock_val = 'source_address_group_value' + assert arg == mock_val + + +def test_clone_address_group_items_flattened_error(): + client = OrganizationAddressGroupServiceClient( + 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.clone_address_group_items( + gcn_address_group.CloneAddressGroupItemsRequest(), + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + +@pytest.mark.asyncio +async def test_clone_address_group_items_flattened_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.clone_address_group_items( + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + arg = args[0].source_address_group + mock_val = 'source_address_group_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_clone_address_group_items_flattened_error_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.clone_address_group_items( + gcn_address_group.CloneAddressGroupItemsRequest(), + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + + +@pytest.mark.parametrize("request_type", [ + address_group.DeleteAddressGroupRequest, + dict, +]) +def test_delete_address_group(request_type, transport: str = 'grpc'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = address_group.DeleteAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_address_group_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = address_group.DeleteAddressGroupRequest( + name='name_value', + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_address_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == address_group.DeleteAddressGroupRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_address_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_address_group] = mock_rpc + request = {} + client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_address_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_address_group] = mock_rpc + + request = {} + await client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_address_group_async(transport: str = 'grpc_asyncio', request_type=address_group.DeleteAddressGroupRequest): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = address_group.DeleteAddressGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_address_group_async_from_dict(): + await test_delete_address_group_async(request_type=dict) + +def test_delete_address_group_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.DeleteAddressGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_address_group_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = address_group.DeleteAddressGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_address_group(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_address_group_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_address_group( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_address_group_flattened_error(): + client = OrganizationAddressGroupServiceClient( + 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_address_group( + address_group.DeleteAddressGroupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_address_group_flattened_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_address_group( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_address_group_flattened_error_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_address_group( + address_group.DeleteAddressGroupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.ListAddressGroupReferencesRequest, + dict, +]) +def test_list_address_group_references(request_type, transport: str = 'grpc'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group_references), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_address_group.ListAddressGroupReferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupReferencesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_address_group_references_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_address_group.ListAddressGroupReferencesRequest( + address_group='address_group_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_address_group_references(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_address_group.ListAddressGroupReferencesRequest( + address_group='address_group_value', + page_token='page_token_value', + ) + +def test_list_address_group_references_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_address_group_references in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_address_group_references] = mock_rpc + request = {} + client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_address_group_references(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_address_group_references_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_address_group_references in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_address_group_references] = mock_rpc + + request = {} + await client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_address_group_references(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_address_group_references_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.ListAddressGroupReferencesRequest): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_address_group_references), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_address_group.ListAddressGroupReferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupReferencesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_address_group_references_async_from_dict(): + await test_list_address_group_references_async(request_type=dict) + +def test_list_address_group_references_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.ListAddressGroupReferencesRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() + client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'address_group=address_group_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_address_group_references_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_address_group.ListAddressGroupReferencesRequest() + + request.address_group = 'address_group_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse()) + await client.list_address_group_references(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', + 'address_group=address_group_value', + ) in kw['metadata'] + + +def test_list_address_group_references_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_address_group_references( + address_group='address_group_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + + +def test_list_address_group_references_flattened_error(): + client = OrganizationAddressGroupServiceClient( + 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_address_group_references( + gcn_address_group.ListAddressGroupReferencesRequest(), + address_group='address_group_value', + ) + +@pytest.mark.asyncio +async def test_list_address_group_references_flattened_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_address_group_references( + address_group='address_group_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].address_group + mock_val = 'address_group_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_address_group_references_flattened_error_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_address_group_references( + gcn_address_group.ListAddressGroupReferencesRequest(), + address_group='address_group_value', + ) + + +def test_list_address_group_references_pager(transport_name: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='abc', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[], + next_page_token='def', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='ghi', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('address_group', ''), + )), + ) + pager = client.list_address_group_references(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) + for i in results) +def test_list_address_group_references_pages(transport_name: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='abc', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[], + next_page_token='def', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='ghi', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + ), + RuntimeError, + ) + pages = list(client.list_address_group_references(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_address_group_references_async_pager(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='abc', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[], + next_page_token='def', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='ghi', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_address_group_references(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_address_group_references_async_pages(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='abc', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[], + next_page_token='def', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='ghi', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_address_group_references(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_address_groups_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_address_groups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_address_groups] = mock_rpc + + request = {} + client.list_address_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_address_groups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_address_groups_rest_required_fields(request_type=address_group.ListAddressGroupsRequest): + transport_class = transports.OrganizationAddressGroupServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_groups._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_groups._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", "return_partial_success", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = address_group.ListAddressGroupsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = address_group.ListAddressGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_address_groups(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_address_groups_rest_unset_required_fields(): + transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_address_groups._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "returnPartialSuccess", )) & set(("parent", ))) + + +def test_list_address_groups_rest_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = address_group.ListAddressGroupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = address_group.ListAddressGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_address_groups(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=organizations/*/locations/*}/addressGroups" % client.transport._host, args[1]) + + +def test_list_address_groups_rest_flattened_error(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_address_groups( + address_group.ListAddressGroupsRequest(), + parent='parent_value', + ) + + +def test_list_address_groups_rest_pager(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + next_page_token='abc', + ), + address_group.ListAddressGroupsResponse( + address_groups=[], + next_page_token='def', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + ], + next_page_token='ghi', + ), + address_group.ListAddressGroupsResponse( + address_groups=[ + address_group.AddressGroup(), + address_group.AddressGroup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(address_group.ListAddressGroupsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'organizations/sample1/locations/sample2'} + + pager = client.list_address_groups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, address_group.AddressGroup) + for i in results) + + pages = list(client.list_address_groups(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_address_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_address_group] = mock_rpc + + request = {} + client.get_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_address_group_rest_required_fields(request_type=address_group.GetAddressGroupRequest): + transport_class = transports.OrganizationAddressGroupServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_address_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_address_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = address_group.AddressGroup() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = address_group.AddressGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_address_group(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_address_group_rest_unset_required_fields(): + transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_address_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_address_group_rest_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = address_group.AddressGroup() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = address_group.AddressGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_address_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=organizations/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + + +def test_get_address_group_rest_flattened_error(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_address_group( + address_group.GetAddressGroupRequest(), + name='name_value', + ) + + +def test_create_address_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_address_group] = mock_rpc + + request = {} + client.create_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_address_group_rest_required_fields(request_type=gcn_address_group.CreateAddressGroupRequest): + transport_class = transports.OrganizationAddressGroupServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["address_group_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "addressGroupId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_address_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "addressGroupId" in jsonified_request + assert jsonified_request["addressGroupId"] == request_init["address_group_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["addressGroupId"] = 'address_group_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_address_group._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("address_group_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "addressGroupId" in jsonified_request + assert jsonified_request["addressGroupId"] == 'address_group_id_value' + + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_address_group(request) + + expected_params = [ + ( + "addressGroupId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_address_group_rest_unset_required_fields(): + transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_address_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(("addressGroupId", "requestId", )) & set(("parent", "addressGroupId", "addressGroup", ))) + + +def test_create_address_group_rest_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'organizations/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_address_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=organizations/*/locations/*}/addressGroups" % client.transport._host, args[1]) + + +def test_create_address_group_rest_flattened_error(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_address_group( + gcn_address_group.CreateAddressGroupRequest(), + parent='parent_value', + address_group=gcn_address_group.AddressGroup(name='name_value'), + address_group_id='address_group_id_value', + ) + + +def test_update_address_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_address_group] = mock_rpc + + request = {} + client.update_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_address_group_rest_required_fields(request_type=gcn_address_group.UpdateAddressGroupRequest): + transport_class = transports.OrganizationAddressGroupServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_address_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_address_group._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_address_group(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_address_group_rest_unset_required_fields(): + transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_address_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("addressGroup", ))) + + +def test_update_address_group_rest_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'address_group': {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_address_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{address_group.name=organizations/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + + +def test_update_address_group_rest_flattened_error(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_address_group( + gcn_address_group.UpdateAddressGroupRequest(), + address_group=gcn_address_group.AddressGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_add_address_group_items_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.add_address_group_items] = mock_rpc + + request = {} + client.add_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_add_address_group_items_rest_required_fields(request_type=gcn_address_group.AddAddressGroupItemsRequest): + transport_class = transports.OrganizationAddressGroupServiceRestTransport + + request_init = {} + request_init["address_group"] = "" + request_init["items"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["addressGroup"] = 'address_group_value' + jsonified_request["items"] = 'items_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "addressGroup" in jsonified_request + assert jsonified_request["addressGroup"] == 'address_group_value' + assert "items" in jsonified_request + assert jsonified_request["items"] == 'items_value' + + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.add_address_group_items(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_add_address_group_items_rest_unset_required_fields(): + transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.add_address_group_items._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("addressGroup", "items", ))) + + +def test_add_address_group_items_rest_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + address_group='address_group_value', + items=['items_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.add_address_group_items(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:addItems" % client.transport._host, args[1]) + + +def test_add_address_group_items_rest_flattened_error(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_address_group_items( + gcn_address_group.AddAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + + +def test_remove_address_group_items_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.remove_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.remove_address_group_items] = mock_rpc + + request = {} + client.remove_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.remove_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_remove_address_group_items_rest_required_fields(request_type=gcn_address_group.RemoveAddressGroupItemsRequest): + transport_class = transports.OrganizationAddressGroupServiceRestTransport + + request_init = {} + request_init["address_group"] = "" + request_init["items"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["addressGroup"] = 'address_group_value' + jsonified_request["items"] = 'items_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "addressGroup" in jsonified_request + assert jsonified_request["addressGroup"] == 'address_group_value' + assert "items" in jsonified_request + assert jsonified_request["items"] == 'items_value' + + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.remove_address_group_items(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_remove_address_group_items_rest_unset_required_fields(): + transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.remove_address_group_items._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("addressGroup", "items", ))) + + +def test_remove_address_group_items_rest_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + address_group='address_group_value', + items=['items_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.remove_address_group_items(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:removeItems" % client.transport._host, args[1]) + + +def test_remove_address_group_items_rest_flattened_error(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_address_group_items( + gcn_address_group.RemoveAddressGroupItemsRequest(), + address_group='address_group_value', + items=['items_value'], + ) + + +def test_clone_address_group_items_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.clone_address_group_items in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.clone_address_group_items] = mock_rpc + + request = {} + client.clone_address_group_items(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.clone_address_group_items(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_clone_address_group_items_rest_required_fields(request_type=gcn_address_group.CloneAddressGroupItemsRequest): + transport_class = transports.OrganizationAddressGroupServiceRestTransport + + request_init = {} + request_init["address_group"] = "" + request_init["source_address_group"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clone_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["addressGroup"] = 'address_group_value' + jsonified_request["sourceAddressGroup"] = 'source_address_group_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clone_address_group_items._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "addressGroup" in jsonified_request + assert jsonified_request["addressGroup"] == 'address_group_value' + assert "sourceAddressGroup" in jsonified_request + assert jsonified_request["sourceAddressGroup"] == 'source_address_group_value' + + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.clone_address_group_items(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_clone_address_group_items_rest_unset_required_fields(): + transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.clone_address_group_items._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("addressGroup", "sourceAddressGroup", ))) + + +def test_clone_address_group_items_rest_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.clone_address_group_items(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:cloneItems" % client.transport._host, args[1]) + + +def test_clone_address_group_items_rest_flattened_error(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.clone_address_group_items( + gcn_address_group.CloneAddressGroupItemsRequest(), + address_group='address_group_value', + source_address_group='source_address_group_value', + ) + + +def test_delete_address_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_address_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_address_group] = mock_rpc + + request = {} + client.delete_address_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_address_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_address_group_rest_required_fields(request_type=address_group.DeleteAddressGroupRequest): + transport_class = transports.OrganizationAddressGroupServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_address_group._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_address_group._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_address_group(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_address_group_rest_unset_required_fields(): + transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_address_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +def test_delete_address_group_rest_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_address_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=organizations/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + + +def test_delete_address_group_rest_flattened_error(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_address_group( + address_group.DeleteAddressGroupRequest(), + name='name_value', + ) + + +def test_list_address_group_references_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_address_group_references in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_address_group_references] = mock_rpc + + request = {} + client.list_address_group_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_address_group_references(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_address_group_references_rest_required_fields(request_type=gcn_address_group.ListAddressGroupReferencesRequest): + transport_class = transports.OrganizationAddressGroupServiceRestTransport + + request_init = {} + request_init["address_group"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_group_references._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["addressGroup"] = 'address_group_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_group_references._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "addressGroup" in jsonified_request + assert jsonified_request["addressGroup"] == 'address_group_value' + + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcn_address_group.ListAddressGroupReferencesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_address_group_references(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_address_group_references_rest_unset_required_fields(): + transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_address_group_references._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("addressGroup", ))) + + +def test_list_address_group_references_rest_flattened(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcn_address_group.ListAddressGroupReferencesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + address_group='address_group_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_address_group_references(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:listReferences" % client.transport._host, args[1]) + + +def test_list_address_group_references_rest_flattened_error(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_address_group_references( + gcn_address_group.ListAddressGroupReferencesRequest(), + address_group='address_group_value', + ) + + +def test_list_address_group_references_rest_pager(transport: str = 'rest'): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='abc', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[], + next_page_token='def', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + next_page_token='ghi', + ), + gcn_address_group.ListAddressGroupReferencesResponse( + address_group_references=[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(gcn_address_group.ListAddressGroupReferencesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + + pager = client.list_address_group_references(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) + for i in results) + + pages = list(client.list_address_group_references(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OrganizationAddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OrganizationAddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationAddressGroupServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OrganizationAddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OrganizationAddressGroupServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OrganizationAddressGroupServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OrganizationAddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationAddressGroupServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OrganizationAddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OrganizationAddressGroupServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OrganizationAddressGroupServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.OrganizationAddressGroupServiceGrpcTransport, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + transports.OrganizationAddressGroupServiceRestTransport, +]) +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_kind_grpc(): + transport = OrganizationAddressGroupServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_address_groups_empty_call_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + call.return_value = address_group.ListAddressGroupsResponse() + client.list_address_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.ListAddressGroupsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_address_group_empty_call_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + call.return_value = address_group.AddressGroup() + client.get_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.GetAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_address_group_empty_call_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CreateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_address_group_empty_call_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.UpdateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_address_group_items_empty_call_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.add_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.AddAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_address_group_items_empty_call_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.remove_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.RemoveAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_clone_address_group_items_empty_call_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.clone_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CloneAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_address_group_empty_call_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.DeleteAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_address_group_references_empty_call_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() + client.list_address_group_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.ListAddressGroupReferencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = OrganizationAddressGroupServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_address_groups_empty_call_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_address_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.ListAddressGroupsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_address_group_empty_call_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup( + name='name_value', + description='description_value', + type_=address_group.AddressGroup.Type.IPV4, + items=['items_value'], + capacity=846, + self_link='self_link_value', + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + )) + await client.get_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.GetAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_address_group_empty_call_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CreateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_address_group_empty_call_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.UpdateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_add_address_group_items_empty_call_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.add_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.AddAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_remove_address_group_items_empty_call_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.remove_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.RemoveAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_clone_address_group_items_empty_call_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.clone_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CloneAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_address_group_empty_call_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.DeleteAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_address_group_references_empty_call_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token='next_page_token_value', + )) + await client.list_address_group_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.ListAddressGroupReferencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = OrganizationAddressGroupServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_address_groups_rest_bad_request(request_type=address_group.ListAddressGroupsRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_address_groups(request) + + +@pytest.mark.parametrize("request_type", [ + address_group.ListAddressGroupsRequest, + dict, +]) +def test_list_address_groups_rest_call_success(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = address_group.ListAddressGroupsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = address_group.ListAddressGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_address_groups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_address_groups_rest_interceptors(null_interceptor): + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) + client = OrganizationAddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_list_address_groups") as post, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_list_address_groups_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_list_address_groups") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = address_group.ListAddressGroupsRequest.pb(address_group.ListAddressGroupsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = address_group.ListAddressGroupsResponse.to_json(address_group.ListAddressGroupsResponse()) + req.return_value.content = return_value + + request = address_group.ListAddressGroupsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = address_group.ListAddressGroupsResponse() + post_with_metadata.return_value = address_group.ListAddressGroupsResponse(), metadata + + client.list_address_groups(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_address_group_rest_bad_request(request_type=address_group.GetAddressGroupRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_address_group(request) + + +@pytest.mark.parametrize("request_type", [ + address_group.GetAddressGroupRequest, + dict, +]) +def test_get_address_group_rest_call_success(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = address_group.AddressGroup( + name='name_value', + description='description_value', + type_=address_group.AddressGroup.Type.IPV4, + items=['items_value'], + capacity=846, + self_link='self_link_value', + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = address_group.AddressGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_address_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, address_group.AddressGroup) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.type_ == address_group.AddressGroup.Type.IPV4 + assert response.items == ['items_value'] + assert response.capacity == 846 + assert response.self_link == 'self_link_value' + assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_address_group_rest_interceptors(null_interceptor): + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) + client = OrganizationAddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_get_address_group") as post, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_get_address_group_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_get_address_group") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = address_group.GetAddressGroupRequest.pb(address_group.GetAddressGroupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = address_group.AddressGroup.to_json(address_group.AddressGroup()) + req.return_value.content = return_value + + request = address_group.GetAddressGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = address_group.AddressGroup() + post_with_metadata.return_value = address_group.AddressGroup(), metadata + + client.get_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_address_group_rest_bad_request(request_type=gcn_address_group.CreateAddressGroupRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_address_group(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.CreateAddressGroupRequest, + dict, +]) +def test_create_address_group_rest_call_success(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'organizations/sample1/locations/sample2'} + request_init["address_group"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'items': ['items_value1', 'items_value2'], 'capacity': 846, 'self_link': 'self_link_value', 'purpose': [1]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_address_group.CreateAddressGroupRequest.meta.fields["address_group"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["address_group"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["address_group"][field])): + del request_init["address_group"][field][i][subfield] + else: + del request_init["address_group"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_address_group(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_address_group_rest_interceptors(null_interceptor): + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) + client = OrganizationAddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_create_address_group") as post, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_create_address_group_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_create_address_group") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.CreateAddressGroupRequest.pb(gcn_address_group.CreateAddressGroupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_address_group.CreateAddressGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_address_group_rest_bad_request(request_type=gcn_address_group.UpdateAddressGroupRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'address_group': {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_address_group(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.UpdateAddressGroupRequest, + dict, +]) +def test_update_address_group_rest_call_success(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'address_group': {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'}} + request_init["address_group"] = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'items': ['items_value1', 'items_value2'], 'capacity': 846, 'self_link': 'self_link_value', 'purpose': [1]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_address_group.UpdateAddressGroupRequest.meta.fields["address_group"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["address_group"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["address_group"][field])): + del request_init["address_group"][field][i][subfield] + else: + del request_init["address_group"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_address_group(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_address_group_rest_interceptors(null_interceptor): + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) + client = OrganizationAddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_update_address_group") as post, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_update_address_group_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_update_address_group") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.UpdateAddressGroupRequest.pb(gcn_address_group.UpdateAddressGroupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_address_group.UpdateAddressGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_add_address_group_items_rest_bad_request(request_type=gcn_address_group.AddAddressGroupItemsRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.add_address_group_items(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.AddAddressGroupItemsRequest, + dict, +]) +def test_add_address_group_items_rest_call_success(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.add_address_group_items(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_add_address_group_items_rest_interceptors(null_interceptor): + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) + client = OrganizationAddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_add_address_group_items") as post, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_add_address_group_items_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_add_address_group_items") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.AddAddressGroupItemsRequest.pb(gcn_address_group.AddAddressGroupItemsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_address_group.AddAddressGroupItemsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.add_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_remove_address_group_items_rest_bad_request(request_type=gcn_address_group.RemoveAddressGroupItemsRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.remove_address_group_items(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.RemoveAddressGroupItemsRequest, + dict, +]) +def test_remove_address_group_items_rest_call_success(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.remove_address_group_items(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_remove_address_group_items_rest_interceptors(null_interceptor): + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) + client = OrganizationAddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_remove_address_group_items") as post, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_remove_address_group_items_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_remove_address_group_items") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.RemoveAddressGroupItemsRequest.pb(gcn_address_group.RemoveAddressGroupItemsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_address_group.RemoveAddressGroupItemsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.remove_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_clone_address_group_items_rest_bad_request(request_type=gcn_address_group.CloneAddressGroupItemsRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.clone_address_group_items(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.CloneAddressGroupItemsRequest, + dict, +]) +def test_clone_address_group_items_rest_call_success(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.clone_address_group_items(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_clone_address_group_items_rest_interceptors(null_interceptor): + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) + client = OrganizationAddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_clone_address_group_items") as post, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_clone_address_group_items_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_clone_address_group_items") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.CloneAddressGroupItemsRequest.pb(gcn_address_group.CloneAddressGroupItemsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_address_group.CloneAddressGroupItemsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.clone_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_address_group_rest_bad_request(request_type=address_group.DeleteAddressGroupRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_address_group(request) + + +@pytest.mark.parametrize("request_type", [ + address_group.DeleteAddressGroupRequest, + dict, +]) +def test_delete_address_group_rest_call_success(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_address_group(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_address_group_rest_interceptors(null_interceptor): + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) + client = OrganizationAddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_delete_address_group") as post, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_delete_address_group_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_delete_address_group") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = address_group.DeleteAddressGroupRequest.pb(address_group.DeleteAddressGroupRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = address_group.DeleteAddressGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_address_group_references_rest_bad_request(request_type=gcn_address_group.ListAddressGroupReferencesRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_address_group_references(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_address_group.ListAddressGroupReferencesRequest, + dict, +]) +def test_list_address_group_references_rest_call_success(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_address_group_references(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAddressGroupReferencesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_address_group_references_rest_interceptors(null_interceptor): + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) + client = OrganizationAddressGroupServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_list_address_group_references") as post, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_list_address_group_references_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_list_address_group_references") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_address_group.ListAddressGroupReferencesRequest.pb(gcn_address_group.ListAddressGroupReferencesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcn_address_group.ListAddressGroupReferencesResponse.to_json(gcn_address_group.ListAddressGroupReferencesResponse()) + req.return_value.content = return_value + + request = gcn_address_group.ListAddressGroupReferencesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcn_address_group.ListAddressGroupReferencesResponse() + post_with_metadata.return_value = gcn_address_group.ListAddressGroupReferencesResponse(), metadata + + client.list_address_group_references(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_initialize_client_w_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_address_groups_empty_call_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_groups), + '__call__') as call: + client.list_address_groups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.ListAddressGroupsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_address_group_empty_call_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_address_group), + '__call__') as call: + client.get_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.GetAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_address_group_empty_call_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_address_group), + '__call__') as call: + client.create_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CreateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_address_group_empty_call_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_address_group), + '__call__') as call: + client.update_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.UpdateAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_add_address_group_items_empty_call_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_address_group_items), + '__call__') as call: + client.add_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.AddAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_remove_address_group_items_empty_call_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.remove_address_group_items), + '__call__') as call: + client.remove_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.RemoveAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_clone_address_group_items_empty_call_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.clone_address_group_items), + '__call__') as call: + client.clone_address_group_items(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.CloneAddressGroupItemsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_address_group_empty_call_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_address_group), + '__call__') as call: + client.delete_address_group(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = address_group.DeleteAddressGroupRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_address_group_references_empty_call_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_address_group_references), + '__call__') as call: + client.list_address_group_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_address_group.ListAddressGroupReferencesRequest() + + assert args[0] == request_msg + + +def test_organization_address_group_service_rest_lro_client(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, +operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.OrganizationAddressGroupServiceGrpcTransport, + ) + +def test_organization_address_group_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OrganizationAddressGroupServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_organization_address_group_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.OrganizationAddressGroupServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_address_groups', + 'get_address_group', + 'create_address_group', + 'update_address_group', + 'add_address_group_items', + 'remove_address_group_items', + 'clone_address_group_items', + 'delete_address_group', + 'list_address_group_references', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_organization_address_group_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.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrganizationAddressGroupServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_organization_address_group_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.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrganizationAddressGroupServiceTransport() + adc.assert_called_once() + + +def test_organization_address_group_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) + OrganizationAddressGroupServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationAddressGroupServiceGrpcTransport, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + ], +) +def test_organization_address_group_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.OrganizationAddressGroupServiceGrpcTransport, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + transports.OrganizationAddressGroupServiceRestTransport, + ], +) +def test_organization_address_group_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.OrganizationAddressGroupServiceGrpcTransport, grpc_helpers), + (transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_organization_address_group_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( + "networksecurity.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="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.OrganizationAddressGroupServiceGrpcTransport, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport]) +def test_organization_address_group_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_organization_address_group_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.OrganizationAddressGroupServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_organization_address_group_service_host_no_port(transport_name): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networksecurity.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_organization_address_group_service_host_with_port(transport_name): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networksecurity.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networksecurity.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_organization_address_group_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = OrganizationAddressGroupServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = OrganizationAddressGroupServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_address_groups._session + session2 = client2.transport.list_address_groups._session + assert session1 != session2 + session1 = client1.transport.get_address_group._session + session2 = client2.transport.get_address_group._session + assert session1 != session2 + session1 = client1.transport.create_address_group._session + session2 = client2.transport.create_address_group._session + assert session1 != session2 + session1 = client1.transport.update_address_group._session + session2 = client2.transport.update_address_group._session + assert session1 != session2 + session1 = client1.transport.add_address_group_items._session + session2 = client2.transport.add_address_group_items._session + assert session1 != session2 + session1 = client1.transport.remove_address_group_items._session + session2 = client2.transport.remove_address_group_items._session + assert session1 != session2 + session1 = client1.transport.clone_address_group_items._session + session2 = client2.transport.clone_address_group_items._session + assert session1 != session2 + session1 = client1.transport.delete_address_group._session + session2 = client2.transport.delete_address_group._session + assert session1 != session2 + session1 = client1.transport.list_address_group_references._session + session2 = client2.transport.list_address_group_references._session + assert session1 != session2 +def test_organization_address_group_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OrganizationAddressGroupServiceGrpcTransport( + 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_organization_address_group_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport( + 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.OrganizationAddressGroupServiceGrpcTransport, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport]) +def test_organization_address_group_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.OrganizationAddressGroupServiceGrpcTransport, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport]) +def test_organization_address_group_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_organization_address_group_service_grpc_lro_client(): + client = OrganizationAddressGroupServiceClient( + 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_organization_address_group_service_grpc_lro_async_client(): + client = OrganizationAddressGroupServiceAsyncClient( + 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_address_group_path(): + project = "squid" + location = "clam" + address_group = "whelk" + expected = "projects/{project}/locations/{location}/addressGroups/{address_group}".format(project=project, location=location, address_group=address_group, ) + actual = OrganizationAddressGroupServiceClient.address_group_path(project, location, address_group) + assert expected == actual + + +def test_parse_address_group_path(): + expected = { + "project": "octopus", + "location": "oyster", + "address_group": "nudibranch", + } + path = OrganizationAddressGroupServiceClient.address_group_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationAddressGroupServiceClient.parse_address_group_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = OrganizationAddressGroupServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = OrganizationAddressGroupServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationAddressGroupServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = OrganizationAddressGroupServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = OrganizationAddressGroupServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationAddressGroupServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = OrganizationAddressGroupServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = OrganizationAddressGroupServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationAddressGroupServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = OrganizationAddressGroupServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = OrganizationAddressGroupServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationAddressGroupServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = OrganizationAddressGroupServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = OrganizationAddressGroupServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationAddressGroupServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.OrganizationAddressGroupServiceTransport, '_prep_wrapped_messages') as prep: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.OrganizationAddressGroupServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = OrganizationAddressGroupServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = OrganizationAddressGroupServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = OrganizationAddressGroupServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport), + (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/.coveragerc b/owl-bot-staging/google-cloud-network-security/v1alpha1/.coveragerc new file mode 100644 index 000000000000..ed01d62f0f9a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/network_security/__init__.py + google/cloud/network_security/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/.flake8 b/owl-bot-staging/google-cloud-network-security/v1alpha1/.flake8 new file mode 100644 index 000000000000..90316de21489 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/.flake8 @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +[flake8] +# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): +# Resolve flake8 lint issues +ignore = E203, E231, E266, E501, W503 +exclude = + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): + # Ensure that generated code passes flake8 lint + **/gapic/** + **/services/** + **/types/** + # Exclude Protobuf gencode + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/LICENSE b/owl-bot-staging/google-cloud-network-security/v1alpha1/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT 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/google-cloud-network-security/v1alpha1/MANIFEST.in b/owl-bot-staging/google-cloud-network-security/v1alpha1/MANIFEST.in new file mode 100644 index 000000000000..dae249ec8976 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/MANIFEST.in @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +include README.rst LICENSE +recursive-include google *.py *.pyi *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/README.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/README.rst new file mode 100644 index 000000000000..fed4f0a4d3c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Cloud Network Security 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 Network Security 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 + + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + + +Examples +^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + + +Examples +^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_templates/layout.html b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_templates/layout.html new file mode 100644 index 000000000000..95e9c77fcfe1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/conf.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/conf.py new file mode 100644 index 000000000000..cf26b0443b74 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/conf.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-network-security 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("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.5.0" + +# 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.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-network-security" +copyright = u"2025, Google, LLC" +author = u"Google APIs" + +# 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", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# 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 google-cloud-network-security", + "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-network-security-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-network-security.tex", + u"google-cloud-network-security Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-network-security", + "google-cloud-network-security Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-network-security", + "google-cloud-network-security Documentation", + author, + "google-cloud-network-security", + "google-cloud-network-security Library", + "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": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", 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/google-cloud-network-security/v1alpha1/docs/index.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/index.rst new file mode 100644 index 000000000000..375cdc60fc09 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/index.rst @@ -0,0 +1,10 @@ +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + network_security_v1alpha1/services_ + network_security_v1alpha1/types_ diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/multiprocessing.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/network_security.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/network_security.rst new file mode 100644 index 000000000000..2d5c286998bb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/network_security.rst @@ -0,0 +1,10 @@ +NetworkSecurity +--------------------------------- + +.. automodule:: google.cloud.network_security_v1alpha1.services.network_security + :members: + :inherited-members: + +.. automodule:: google.cloud.network_security_v1alpha1.services.network_security.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/services_.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/services_.rst new file mode 100644 index 000000000000..c516f66fcc1b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Network Security v1alpha1 API +======================================================= +.. toctree:: + :maxdepth: 2 + + network_security diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/types_.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/types_.rst new file mode 100644 index 000000000000..acd342bb784d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Network Security v1alpha1 API +==================================================== + +.. automodule:: google.cloud.network_security_v1alpha1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/__init__.py new file mode 100644 index 000000000000..583572715ec7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/__init__.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.network_security import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.network_security_v1alpha1.services.network_security.client import NetworkSecurityClient +from google.cloud.network_security_v1alpha1.services.network_security.async_client import NetworkSecurityAsyncClient + +from google.cloud.network_security_v1alpha1.types.client_tls_policy import ClientTlsPolicy +from google.cloud.network_security_v1alpha1.types.client_tls_policy import CreateClientTlsPolicyRequest +from google.cloud.network_security_v1alpha1.types.client_tls_policy import DeleteClientTlsPolicyRequest +from google.cloud.network_security_v1alpha1.types.client_tls_policy import GetClientTlsPolicyRequest +from google.cloud.network_security_v1alpha1.types.client_tls_policy import ListClientTlsPoliciesRequest +from google.cloud.network_security_v1alpha1.types.client_tls_policy import ListClientTlsPoliciesResponse +from google.cloud.network_security_v1alpha1.types.client_tls_policy import UpdateClientTlsPolicyRequest +from google.cloud.network_security_v1alpha1.types.common import OperationMetadata +from google.cloud.network_security_v1alpha1.types.tls import CertificateProvider +from google.cloud.network_security_v1alpha1.types.tls import CertificateProviderInstance +from google.cloud.network_security_v1alpha1.types.tls import GrpcEndpoint +from google.cloud.network_security_v1alpha1.types.tls import ValidationCA + +__all__ = ('NetworkSecurityClient', + 'NetworkSecurityAsyncClient', + 'ClientTlsPolicy', + 'CreateClientTlsPolicyRequest', + 'DeleteClientTlsPolicyRequest', + 'GetClientTlsPolicyRequest', + 'ListClientTlsPoliciesRequest', + 'ListClientTlsPoliciesResponse', + 'UpdateClientTlsPolicyRequest', + 'OperationMetadata', + 'CertificateProvider', + 'CertificateProviderInstance', + 'GrpcEndpoint', + 'ValidationCA', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/py.typed b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/py.typed new file mode 100644 index 000000000000..41b3c3019247 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/__init__.py new file mode 100644 index 000000000000..b12276617bce --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/__init__.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.network_security_v1alpha1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.network_security import NetworkSecurityClient +from .services.network_security import NetworkSecurityAsyncClient + +from .types.client_tls_policy import ClientTlsPolicy +from .types.client_tls_policy import CreateClientTlsPolicyRequest +from .types.client_tls_policy import DeleteClientTlsPolicyRequest +from .types.client_tls_policy import GetClientTlsPolicyRequest +from .types.client_tls_policy import ListClientTlsPoliciesRequest +from .types.client_tls_policy import ListClientTlsPoliciesResponse +from .types.client_tls_policy import UpdateClientTlsPolicyRequest +from .types.common import OperationMetadata +from .types.tls import CertificateProvider +from .types.tls import CertificateProviderInstance +from .types.tls import GrpcEndpoint +from .types.tls import ValidationCA + +__all__ = ( + 'NetworkSecurityAsyncClient', +'CertificateProvider', +'CertificateProviderInstance', +'ClientTlsPolicy', +'CreateClientTlsPolicyRequest', +'DeleteClientTlsPolicyRequest', +'GetClientTlsPolicyRequest', +'GrpcEndpoint', +'ListClientTlsPoliciesRequest', +'ListClientTlsPoliciesResponse', +'NetworkSecurityClient', +'OperationMetadata', +'UpdateClientTlsPolicyRequest', +'ValidationCA', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_metadata.json new file mode 100644 index 000000000000..2dcb3d449f64 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_metadata.json @@ -0,0 +1,103 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.network_security_v1alpha1", + "protoPackage": "google.cloud.networksecurity.v1alpha1", + "schema": "1.0", + "services": { + "NetworkSecurity": { + "clients": { + "grpc": { + "libraryClient": "NetworkSecurityClient", + "rpcs": { + "CreateClientTlsPolicy": { + "methods": [ + "create_client_tls_policy" + ] + }, + "DeleteClientTlsPolicy": { + "methods": [ + "delete_client_tls_policy" + ] + }, + "GetClientTlsPolicy": { + "methods": [ + "get_client_tls_policy" + ] + }, + "ListClientTlsPolicies": { + "methods": [ + "list_client_tls_policies" + ] + }, + "UpdateClientTlsPolicy": { + "methods": [ + "update_client_tls_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "NetworkSecurityAsyncClient", + "rpcs": { + "CreateClientTlsPolicy": { + "methods": [ + "create_client_tls_policy" + ] + }, + "DeleteClientTlsPolicy": { + "methods": [ + "delete_client_tls_policy" + ] + }, + "GetClientTlsPolicy": { + "methods": [ + "get_client_tls_policy" + ] + }, + "ListClientTlsPolicies": { + "methods": [ + "list_client_tls_policies" + ] + }, + "UpdateClientTlsPolicy": { + "methods": [ + "update_client_tls_policy" + ] + } + } + }, + "rest": { + "libraryClient": "NetworkSecurityClient", + "rpcs": { + "CreateClientTlsPolicy": { + "methods": [ + "create_client_tls_policy" + ] + }, + "DeleteClientTlsPolicy": { + "methods": [ + "delete_client_tls_policy" + ] + }, + "GetClientTlsPolicy": { + "methods": [ + "get_client_tls_policy" + ] + }, + "ListClientTlsPolicies": { + "methods": [ + "list_client_tls_policies" + ] + }, + "UpdateClientTlsPolicy": { + "methods": [ + "update_client_tls_policy" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/py.typed b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/py.typed new file mode 100644 index 000000000000..41b3c3019247 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/__init__.py new file mode 100644 index 000000000000..cddb3cfba9e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 NetworkSecurityClient +from .async_client import NetworkSecurityAsyncClient + +__all__ = ( + 'NetworkSecurityClient', + 'NetworkSecurityAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/async_client.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/async_client.py new file mode 100644 index 000000000000..8d885d988570 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/async_client.py @@ -0,0 +1,1539 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.network_security_v1alpha1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1alpha1.services.network_security import pagers +from google.cloud.network_security_v1alpha1.types import client_tls_policy +from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1alpha1.types import common +from google.cloud.network_security_v1alpha1.types import tls +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport +from .client import NetworkSecurityClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class NetworkSecurityAsyncClient: + """Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + """ + + _client: NetworkSecurityClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = NetworkSecurityClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = NetworkSecurityClient._DEFAULT_UNIVERSE + + client_tls_policy_path = staticmethod(NetworkSecurityClient.client_tls_policy_path) + parse_client_tls_policy_path = staticmethod(NetworkSecurityClient.parse_client_tls_policy_path) + common_billing_account_path = staticmethod(NetworkSecurityClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(NetworkSecurityClient.parse_common_billing_account_path) + common_folder_path = staticmethod(NetworkSecurityClient.common_folder_path) + parse_common_folder_path = staticmethod(NetworkSecurityClient.parse_common_folder_path) + common_organization_path = staticmethod(NetworkSecurityClient.common_organization_path) + parse_common_organization_path = staticmethod(NetworkSecurityClient.parse_common_organization_path) + common_project_path = staticmethod(NetworkSecurityClient.common_project_path) + parse_common_project_path = staticmethod(NetworkSecurityClient.parse_common_project_path) + common_location_path = staticmethod(NetworkSecurityClient.common_location_path) + parse_common_location_path = staticmethod(NetworkSecurityClient.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: + NetworkSecurityAsyncClient: The constructed client. + """ + return NetworkSecurityClient.from_service_account_info.__func__(NetworkSecurityAsyncClient, 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: + NetworkSecurityAsyncClient: The constructed client. + """ + return NetworkSecurityClient.from_service_account_file.__func__(NetworkSecurityAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return NetworkSecurityClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> NetworkSecurityTransport: + """Returns the transport used by the client instance. + + Returns: + NetworkSecurityTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = NetworkSecurityClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the network security async 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the NetworkSecurityTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = NetworkSecurityClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient`.", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "credentialsType": None, + } + ) + + async def list_client_tls_policies(self, + request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListClientTlsPoliciesAsyncPager: + r"""Lists ClientTlsPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1alpha1 + + async def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest, dict]]): + The request object. Request used by the + ListClientTlsPolicies method. + parent (:class:`str`): + Required. The project and location from which the + ClientTlsPolicies should be listed, specified in the + format ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1alpha1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager: + Response returned by the + ListClientTlsPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): + request = client_tls_policy.ListClientTlsPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_client_tls_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListClientTlsPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_client_tls_policy(self, + request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> client_tls_policy.ClientTlsPolicy: + r"""Gets details of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1alpha1 + + async def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1alpha1.types.GetClientTlsPolicyRequest, dict]]): + The request object. Request used by the + GetClientTlsPolicy method. + name (:class:`str`): + Required. A name of the ClientTlsPolicy to get. Must be + in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1alpha1.types.ClientTlsPolicy: + ClientTlsPolicy is a resource that + specifies how a client should + authenticate connections to backends of + a service. This resource itself does not + affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): + request = client_tls_policy.GetClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + client_tls_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ClientTlsPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1alpha1 + + async def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1alpha1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1alpha1.types.CreateClientTlsPolicyRequest, dict]]): + The request object. Request used by the + CreateClientTlsPolicy method. + parent (:class:`str`): + Required. The parent resource of the ClientTlsPolicy. + Must be in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy (:class:`google.cloud.network_security_v1alpha1.types.ClientTlsPolicy`): + Required. ClientTlsPolicy resource to + be created. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy_id (:class:`str`): + Required. Short name of the ClientTlsPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "client_mtls_policy". + + This corresponds to the ``client_tls_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1alpha1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, client_tls_policy, client_tls_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if client_tls_policy_id is not None: + request.client_tls_policy_id = client_tls_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, + *, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1alpha1 + + async def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1alpha1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1alpha1.types.UpdateClientTlsPolicyRequest, dict]]): + The request object. Request used by UpdateClientTlsPolicy + method. + client_tls_policy (:class:`google.cloud.network_security_v1alpha1.types.ClientTlsPolicy`): + Required. Updated ClientTlsPolicy + resource. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the ClientTlsPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1alpha1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [client_tls_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_client_tls_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("client_tls_policy.name", request.client_tls_policy.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_client_tls_policy(self, + request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1alpha1 + + async def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1alpha1.types.DeleteClientTlsPolicyRequest, dict]]): + The request object. Request used by the + DeleteClientTlsPolicy method. + name (:class:`str`): + Required. A name of the ClientTlsPolicy to delete. Must + be in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): + request = client_tls_policy.DeleteClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "NetworkSecurityAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "NetworkSecurityAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/client.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/client.py new file mode 100644 index 000000000000..c166889d6e8f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/client.py @@ -0,0 +1,1918 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.network_security_v1alpha1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1alpha1.services.network_security import pagers +from google.cloud.network_security_v1alpha1.types import client_tls_policy +from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1alpha1.types import common +from google.cloud.network_security_v1alpha1.types import tls +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import NetworkSecurityGrpcTransport +from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport +from .transports.rest import NetworkSecurityRestTransport + + +class NetworkSecurityClientMeta(type): + """Metaclass for the NetworkSecurity 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[NetworkSecurityTransport]] + _transport_registry["grpc"] = NetworkSecurityGrpcTransport + _transport_registry["grpc_asyncio"] = NetworkSecurityGrpcAsyncIOTransport + _transport_registry["rest"] = NetworkSecurityRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[NetworkSecurityTransport]: + """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 NetworkSecurityClient(metaclass=NetworkSecurityClientMeta): + """Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "networksecurity.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networksecurity.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + NetworkSecurityClient: 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: + NetworkSecurityClient: 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) -> NetworkSecurityTransport: + """Returns the transport used by the client instance. + + Returns: + NetworkSecurityTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def client_tls_policy_path(project: str,location: str,client_tls_policy: str,) -> str: + """Returns a fully-qualified client_tls_policy string.""" + return "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) + + @staticmethod + def parse_client_tls_policy_path(path: str) -> Dict[str,str]: + """Parses a client_tls_policy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clientTlsPolicies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = NetworkSecurityClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the network security 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the NetworkSecurityTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = NetworkSecurityClient._read_environment_variables() + self._client_cert_source = NetworkSecurityClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = NetworkSecurityClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, NetworkSecurityTransport) + if transport_provided: + # transport is a NetworkSecurityTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(NetworkSecurityTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + NetworkSecurityClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[NetworkSecurityTransport], Callable[..., NetworkSecurityTransport]] = ( + NetworkSecurityClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., NetworkSecurityTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networksecurity_v1alpha1.NetworkSecurityClient`.", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "credentialsType": None, + } + ) + + def list_client_tls_policies(self, + request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListClientTlsPoliciesPager: + r"""Lists ClientTlsPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1alpha1 + + def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest, dict]): + The request object. Request used by the + ListClientTlsPolicies method. + parent (str): + Required. The project and location from which the + ClientTlsPolicies should be listed, specified in the + format ``projects/*/locations/{location}``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1alpha1.services.network_security.pagers.ListClientTlsPoliciesPager: + Response returned by the + ListClientTlsPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): + request = client_tls_policy.ListClientTlsPoliciesRequest(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_client_tls_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListClientTlsPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_client_tls_policy(self, + request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> client_tls_policy.ClientTlsPolicy: + r"""Gets details of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1alpha1 + + def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1alpha1.types.GetClientTlsPolicyRequest, dict]): + The request object. Request used by the + GetClientTlsPolicy method. + name (str): + Required. A name of the ClientTlsPolicy to get. Must be + in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1alpha1.types.ClientTlsPolicy: + ClientTlsPolicy is a resource that + specifies how a client should + authenticate connections to backends of + a service. This resource itself does not + affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): + request = client_tls_policy.GetClientTlsPolicyRequest(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_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + client_tls_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new ClientTlsPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1alpha1 + + def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1alpha1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1alpha1.types.CreateClientTlsPolicyRequest, dict]): + The request object. Request used by the + CreateClientTlsPolicy method. + parent (str): + Required. The parent resource of the ClientTlsPolicy. + Must be in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy (google.cloud.network_security_v1alpha1.types.ClientTlsPolicy): + Required. ClientTlsPolicy resource to + be created. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy_id (str): + Required. Short name of the ClientTlsPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "client_mtls_policy". + + This corresponds to the ``client_tls_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1alpha1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, client_tls_policy, client_tls_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if client_tls_policy_id is not None: + request.client_tls_policy_id = client_tls_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, + *, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1alpha1 + + def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1alpha1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1alpha1.types.UpdateClientTlsPolicyRequest, dict]): + The request object. Request used by UpdateClientTlsPolicy + method. + client_tls_policy (google.cloud.network_security_v1alpha1.types.ClientTlsPolicy): + Required. Updated ClientTlsPolicy + resource. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ClientTlsPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1alpha1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [client_tls_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_client_tls_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("client_tls_policy.name", request.client_tls_policy.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_client_tls_policy(self, + request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1alpha1 + + def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1alpha1.types.DeleteClientTlsPolicyRequest, dict]): + The request object. Request used by the + DeleteClientTlsPolicy method. + name (str): + Required. A name of the ClientTlsPolicy to delete. Must + be in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): + request = client_tls_policy.DeleteClientTlsPolicyRequest(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_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "NetworkSecurityClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "NetworkSecurityClient", +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/pagers.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/pagers.py new file mode 100644 index 000000000000..d1879e70eb7e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/pagers.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.network_security_v1alpha1.types import client_tls_policy + + +class ListClientTlsPoliciesPager: + """A pager for iterating through ``list_client_tls_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``client_tls_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListClientTlsPolicies`` requests and continue to iterate + through the ``client_tls_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse` + 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[..., client_tls_policy.ListClientTlsPoliciesResponse], + request: client_tls_policy.ListClientTlsPoliciesRequest, + response: client_tls_policy.ListClientTlsPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[client_tls_policy.ListClientTlsPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[client_tls_policy.ClientTlsPolicy]: + for page in self.pages: + yield from page.client_tls_policies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListClientTlsPoliciesAsyncPager: + """A pager for iterating through ``list_client_tls_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``client_tls_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListClientTlsPolicies`` requests and continue to iterate + through the ``client_tls_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse` + 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[client_tls_policy.ListClientTlsPoliciesResponse]], + request: client_tls_policy.ListClientTlsPoliciesRequest, + response: client_tls_policy.ListClientTlsPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[client_tls_policy.ListClientTlsPoliciesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[client_tls_policy.ClientTlsPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.client_tls_policies: + 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/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/README.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/README.rst new file mode 100644 index 000000000000..e226a3cdbadb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`NetworkSecurityTransport` is the ABC for all transports. +- public child `NetworkSecurityGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `NetworkSecurityGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseNetworkSecurityRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `NetworkSecurityRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/__init__.py new file mode 100644 index 000000000000..6ee9817a2d9e --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 NetworkSecurityTransport +from .grpc import NetworkSecurityGrpcTransport +from .grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport +from .rest import NetworkSecurityRestTransport +from .rest import NetworkSecurityRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[NetworkSecurityTransport]] +_transport_registry['grpc'] = NetworkSecurityGrpcTransport +_transport_registry['grpc_asyncio'] = NetworkSecurityGrpcAsyncIOTransport +_transport_registry['rest'] = NetworkSecurityRestTransport + +__all__ = ( + 'NetworkSecurityTransport', + 'NetworkSecurityGrpcTransport', + 'NetworkSecurityGrpcAsyncIOTransport', + 'NetworkSecurityRestTransport', + 'NetworkSecurityRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/base.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/base.py new file mode 100644 index 000000000000..de50919c0308 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/base.py @@ -0,0 +1,353 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.network_security_v1alpha1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1alpha1.types import client_tls_policy +from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class NetworkSecurityTransport(abc.ABC): + """Abstract transport class for NetworkSecurity.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'networksecurity.googleapis.com' + + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_client_tls_policies: gapic_v1.method.wrap_method( + self.list_client_tls_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_client_tls_policy: gapic_v1.method.wrap_method( + self.get_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_client_tls_policy: gapic_v1.method.wrap_method( + self.create_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_client_tls_policy: gapic_v1.method.wrap_method( + self.update_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_client_tls_policy: gapic_v1.method.wrap_method( + self.delete_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + Union[ + client_tls_policy.ListClientTlsPoliciesResponse, + Awaitable[client_tls_policy.ListClientTlsPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + Union[ + client_tls_policy.ClientTlsPolicy, + Awaitable[client_tls_policy.ClientTlsPolicy] + ]]: + raise NotImplementedError() + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'NetworkSecurityTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc.py new file mode 100644 index 000000000000..de9a0a9e447c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc.py @@ -0,0 +1,664 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1alpha1.types import client_tls_policy +from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class NetworkSecurityGrpcTransport(NetworkSecurityTransport): + """gRPC backend transport for NetworkSecurity. + + Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + client_tls_policy.ListClientTlsPoliciesResponse]: + r"""Return a callable for the list client tls policies method over gRPC. + + Lists ClientTlsPolicies in a given project and + location. + + Returns: + Callable[[~.ListClientTlsPoliciesRequest], + ~.ListClientTlsPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: + self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/ListClientTlsPolicies', + request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, + response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, + ) + return self._stubs['list_client_tls_policies'] + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + client_tls_policy.ClientTlsPolicy]: + r"""Return a callable for the get client tls policy method over gRPC. + + Gets details of a single ClientTlsPolicy. + + Returns: + Callable[[~.GetClientTlsPolicyRequest], + ~.ClientTlsPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: + self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/GetClientTlsPolicy', + request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, + response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, + ) + return self._stubs['get_client_tls_policy'] + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the create client tls policy method over gRPC. + + Creates a new ClientTlsPolicy in a given project and + location. + + Returns: + Callable[[~.CreateClientTlsPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_client_tls_policy' not in self._stubs: + self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/CreateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_client_tls_policy'] + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the update client tls policy method over gRPC. + + Updates the parameters of a single ClientTlsPolicy. + + Returns: + Callable[[~.UpdateClientTlsPolicyRequest], + ~.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 'update_client_tls_policy' not in self._stubs: + self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/UpdateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_client_tls_policy'] + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete client tls policy method over gRPC. + + Deletes a single ClientTlsPolicy. + + Returns: + Callable[[~.DeleteClientTlsPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_client_tls_policy' not in self._stubs: + self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/DeleteClientTlsPolicy', + request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_client_tls_policy'] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'NetworkSecurityGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc_asyncio.py new file mode 100644 index 000000000000..d86c9fd628f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc_asyncio.py @@ -0,0 +1,750 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1alpha1.types import client_tls_policy +from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO +from .grpc import NetworkSecurityGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class NetworkSecurityGrpcAsyncIOTransport(NetworkSecurityTransport): + """gRPC AsyncIO backend transport for NetworkSecurity. + + Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + Awaitable[client_tls_policy.ListClientTlsPoliciesResponse]]: + r"""Return a callable for the list client tls policies method over gRPC. + + Lists ClientTlsPolicies in a given project and + location. + + Returns: + Callable[[~.ListClientTlsPoliciesRequest], + Awaitable[~.ListClientTlsPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: + self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/ListClientTlsPolicies', + request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, + response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, + ) + return self._stubs['list_client_tls_policies'] + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + Awaitable[client_tls_policy.ClientTlsPolicy]]: + r"""Return a callable for the get client tls policy method over gRPC. + + Gets details of a single ClientTlsPolicy. + + Returns: + Callable[[~.GetClientTlsPolicyRequest], + Awaitable[~.ClientTlsPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: + self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/GetClientTlsPolicy', + request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, + response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, + ) + return self._stubs['get_client_tls_policy'] + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create client tls policy method over gRPC. + + Creates a new ClientTlsPolicy in a given project and + location. + + Returns: + Callable[[~.CreateClientTlsPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_client_tls_policy' not in self._stubs: + self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/CreateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_client_tls_policy'] + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update client tls policy method over gRPC. + + Updates the parameters of a single ClientTlsPolicy. + + Returns: + Callable[[~.UpdateClientTlsPolicyRequest], + 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 'update_client_tls_policy' not in self._stubs: + self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/UpdateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_client_tls_policy'] + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete client tls policy method over gRPC. + + Deletes a single ClientTlsPolicy. + + Returns: + Callable[[~.DeleteClientTlsPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_client_tls_policy' not in self._stubs: + self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/DeleteClientTlsPolicy', + request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_client_tls_policy'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_client_tls_policies: self._wrap_method( + self.list_client_tls_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_client_tls_policy: self._wrap_method( + self.get_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_client_tls_policy: self._wrap_method( + self.create_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_client_tls_policy: self._wrap_method( + self.update_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_client_tls_policy: self._wrap_method( + self.delete_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'NetworkSecurityGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest.py new file mode 100644 index 000000000000..e1452ae85d00 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest.py @@ -0,0 +1,2341 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 +import google.protobuf + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.network_security_v1alpha1.types import client_tls_policy +from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseNetworkSecurityRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class NetworkSecurityRestInterceptor: + """Interceptor for NetworkSecurity. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the NetworkSecurityRestTransport. + + .. code-block:: python + class MyCustomNetworkSecurityInterceptor(NetworkSecurityRestInterceptor): + def pre_create_client_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_client_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_client_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_client_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_client_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_client_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_client_tls_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_client_tls_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_client_tls_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_client_tls_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = NetworkSecurityRestTransport(interceptor=MyCustomNetworkSecurityInterceptor()) + client = NetworkSecurityClient(transport=transport) + + + """ + def pre_create_client_tls_policy(self, request: gcn_client_tls_policy.CreateClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_client_tls_policy.CreateClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_client_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_create_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_client_tls_policy + + DEPRECATED. Please use the `post_create_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_create_client_tls_policy` interceptor runs + before the `post_create_client_tls_policy_with_metadata` interceptor. + """ + return response + + def post_create_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_create_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_create_client_tls_policy` interceptor. + When both interceptors are used, this `post_create_client_tls_policy_with_metadata` interceptor runs after the + `post_create_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_create_client_tls_policy` will be passed to + `post_create_client_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_client_tls_policy(self, request: client_tls_policy.DeleteClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.DeleteClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_client_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_delete_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_client_tls_policy + + DEPRECATED. Please use the `post_delete_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_delete_client_tls_policy` interceptor runs + before the `post_delete_client_tls_policy_with_metadata` interceptor. + """ + return response + + def post_delete_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_delete_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_delete_client_tls_policy` interceptor. + When both interceptors are used, this `post_delete_client_tls_policy_with_metadata` interceptor runs after the + `post_delete_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_delete_client_tls_policy` will be passed to + `post_delete_client_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_get_client_tls_policy(self, request: client_tls_policy.GetClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.GetClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_client_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_get_client_tls_policy(self, response: client_tls_policy.ClientTlsPolicy) -> client_tls_policy.ClientTlsPolicy: + """Post-rpc interceptor for get_client_tls_policy + + DEPRECATED. Please use the `post_get_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_get_client_tls_policy` interceptor runs + before the `post_get_client_tls_policy_with_metadata` interceptor. + """ + return response + + def post_get_client_tls_policy_with_metadata(self, response: client_tls_policy.ClientTlsPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ClientTlsPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_get_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_get_client_tls_policy` interceptor. + When both interceptors are used, this `post_get_client_tls_policy_with_metadata` interceptor runs after the + `post_get_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_get_client_tls_policy` will be passed to + `post_get_client_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_list_client_tls_policies(self, request: client_tls_policy.ListClientTlsPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ListClientTlsPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_client_tls_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_list_client_tls_policies(self, response: client_tls_policy.ListClientTlsPoliciesResponse) -> client_tls_policy.ListClientTlsPoliciesResponse: + """Post-rpc interceptor for list_client_tls_policies + + DEPRECATED. Please use the `post_list_client_tls_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_list_client_tls_policies` interceptor runs + before the `post_list_client_tls_policies_with_metadata` interceptor. + """ + return response + + def post_list_client_tls_policies_with_metadata(self, response: client_tls_policy.ListClientTlsPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ListClientTlsPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_client_tls_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_list_client_tls_policies_with_metadata` + interceptor in new development instead of the `post_list_client_tls_policies` interceptor. + When both interceptors are used, this `post_list_client_tls_policies_with_metadata` interceptor runs after the + `post_list_client_tls_policies` interceptor. The (possibly modified) response returned by + `post_list_client_tls_policies` will be passed to + `post_list_client_tls_policies_with_metadata`. + """ + return response, metadata + + def pre_update_client_tls_policy(self, request: gcn_client_tls_policy.UpdateClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_client_tls_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_update_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_client_tls_policy + + DEPRECATED. Please use the `post_update_client_tls_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. This `post_update_client_tls_policy` interceptor runs + before the `post_update_client_tls_policy_with_metadata` interceptor. + """ + return response + + def post_update_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_client_tls_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the NetworkSecurity server but before it is returned to user code. + + We recommend only using this `post_update_client_tls_policy_with_metadata` + interceptor in new development instead of the `post_update_client_tls_policy` interceptor. + When both interceptors are used, this `post_update_client_tls_policy_with_metadata` interceptor runs after the + `post_update_client_tls_policy` interceptor. The (possibly modified) response returned by + `post_update_client_tls_policy` will be passed to + `post_update_client_tls_policy_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the NetworkSecurity server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the NetworkSecurity server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class NetworkSecurityRestStub: + _session: AuthorizedSession + _host: str + _interceptor: NetworkSecurityRestInterceptor + + +class NetworkSecurityRestTransport(_BaseNetworkSecurityRestTransport): + """REST backend synchronous transport for NetworkSecurity. + + Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[NetworkSecurityRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or NetworkSecurityRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'delete', + 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=organizations/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.CreateClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_client_tls_policy.CreateClientTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create client tls policy method over HTTP. + + Args: + request (~.gcn_client_tls_policy.CreateClientTlsPolicyRequest): + The request object. Request used by the + CreateClientTlsPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_create_client_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.CreateClientTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "CreateClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._CreateClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_client_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.create_client_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "CreateClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.DeleteClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: client_tls_policy.DeleteClientTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete client tls policy method over HTTP. + + Args: + request (~.client_tls_policy.DeleteClientTlsPolicyRequest): + The request object. Request used by the + DeleteClientTlsPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_delete_client_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.DeleteClientTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "DeleteClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._DeleteClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_client_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.delete_client_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "DeleteClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: client_tls_policy.GetClientTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> client_tls_policy.ClientTlsPolicy: + r"""Call the get client tls policy method over HTTP. + + Args: + request (~.client_tls_policy.GetClientTlsPolicyRequest): + The request object. Request used by the + GetClientTlsPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.client_tls_policy.ClientTlsPolicy: + ClientTlsPolicy is a resource that + specifies how a client should + authenticate connections to backends of + a service. This resource itself does not + affect configuration unless it is + attached to a backend service resource. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_client_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.GetClientTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "GetClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._GetClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = client_tls_policy.ClientTlsPolicy() + pb_resp = client_tls_policy.ClientTlsPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_client_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = client_tls_policy.ClientTlsPolicy.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.get_client_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "GetClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListClientTlsPolicies(_BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.ListClientTlsPolicies") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: client_tls_policy.ListClientTlsPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> client_tls_policy.ListClientTlsPoliciesResponse: + r"""Call the list client tls policies method over HTTP. + + Args: + request (~.client_tls_policy.ListClientTlsPoliciesRequest): + The request object. Request used by the + ListClientTlsPolicies method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.client_tls_policy.ListClientTlsPoliciesResponse: + Response returned by the + ListClientTlsPolicies method. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_http_options() + + request, metadata = self._interceptor.pre_list_client_tls_policies(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.ListClientTlsPolicies", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "ListClientTlsPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._ListClientTlsPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = client_tls_policy.ListClientTlsPoliciesResponse() + pb_resp = client_tls_policy.ListClientTlsPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_client_tls_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_client_tls_policies_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = client_tls_policy.ListClientTlsPoliciesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.list_client_tls_policies", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "ListClientTlsPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.UpdateClientTlsPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: gcn_client_tls_policy.UpdateClientTlsPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update client tls policy method over HTTP. + + Args: + request (~.gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + The request object. Request used by UpdateClientTlsPolicy + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_http_options() + + request, metadata = self._interceptor.pre_update_client_tls_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.UpdateClientTlsPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "UpdateClientTlsPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._UpdateClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_client_tls_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_client_tls_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.update_client_tls_policy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "UpdateClientTlsPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + client_tls_policy.ClientTlsPolicy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + client_tls_policy.ListClientTlsPoliciesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListClientTlsPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseNetworkSecurityRestTransport._BaseGetLocation, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_http_options() + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.GetLocation", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.GetLocation", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseNetworkSecurityRestTransport._BaseListLocations, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseListLocations._get_http_options() + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.ListLocations", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.ListLocations", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseNetworkSecurityRestTransport._BaseGetIamPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.GetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.GetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseNetworkSecurityRestTransport._BaseSetIamPolicy, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.SetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.SetIamPolicy", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseNetworkSecurityRestTransport._BaseTestIamPermissions, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.TestIamPermissions", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.TestIamPermissions", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(_BaseNetworkSecurityRestTransport._BaseCancelOperation, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.CancelOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(_BaseNetworkSecurityRestTransport._BaseDeleteOperation, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseNetworkSecurityRestTransport._BaseGetOperation, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.GetOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(_BaseNetworkSecurityRestTransport._BaseListOperations, NetworkSecurityRestStub): + def __hash__(self): + return hash("NetworkSecurityRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseNetworkSecurityRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseNetworkSecurityRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseNetworkSecurityRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) + method = transcoded_request['method'] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.ListOperations", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = NetworkSecurityRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'NetworkSecurityRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest_base.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest_base.py new file mode 100644 index 000000000000..958a3c47aa85 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest_base.py @@ -0,0 +1,614 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.network_security_v1alpha1.types import client_tls_policy +from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseNetworkSecurityRestTransport(NetworkSecurityTransport): + """Base REST backend transport for NetworkSecurity. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[Any]): 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. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseCreateClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "clientTlsPolicyId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/clientTlsPolicies', + 'body': 'client_tls_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clientTlsPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = client_tls_policy.DeleteClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/clientTlsPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = client_tls_policy.GetClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListClientTlsPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{parent=projects/*/locations/*}/clientTlsPolicies', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = client_tls_policy.ListClientTlsPoliciesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateClientTlsPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}', + 'body': 'client_tls_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*}/locations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/authzPolicies/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/authzPolicies/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1alpha1/{resource=projects/*/locations/*/authzPolicies/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'delete', + 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha1/{name=organizations/*/locations/*}/operations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseNetworkSecurityRestTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/__init__.py new file mode 100644 index 000000000000..56e5949f4e2f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/__init__.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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_tls_policy import ( + ClientTlsPolicy, + CreateClientTlsPolicyRequest, + DeleteClientTlsPolicyRequest, + GetClientTlsPolicyRequest, + ListClientTlsPoliciesRequest, + ListClientTlsPoliciesResponse, + UpdateClientTlsPolicyRequest, +) +from .common import ( + OperationMetadata, +) +from .tls import ( + CertificateProvider, + CertificateProviderInstance, + GrpcEndpoint, + ValidationCA, +) + +__all__ = ( + 'ClientTlsPolicy', + 'CreateClientTlsPolicyRequest', + 'DeleteClientTlsPolicyRequest', + 'GetClientTlsPolicyRequest', + 'ListClientTlsPoliciesRequest', + 'ListClientTlsPoliciesResponse', + 'UpdateClientTlsPolicyRequest', + 'OperationMetadata', + 'CertificateProvider', + 'CertificateProviderInstance', + 'GrpcEndpoint', + 'ValidationCA', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/client_tls_policy.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/client_tls_policy.py new file mode 100644 index 000000000000..f40670b490de --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/client_tls_policy.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.network_security_v1alpha1.types import tls +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1alpha1', + manifest={ + 'ClientTlsPolicy', + 'ListClientTlsPoliciesRequest', + 'ListClientTlsPoliciesResponse', + 'GetClientTlsPolicyRequest', + 'CreateClientTlsPolicyRequest', + 'UpdateClientTlsPolicyRequest', + 'DeleteClientTlsPolicyRequest', + }, +) + + +class ClientTlsPolicy(proto.Message): + r"""ClientTlsPolicy is a resource that specifies how a client + should authenticate connections to backends of a service. This + resource itself does not affect configuration unless it is + attached to a backend service resource. + + Attributes: + name (str): + Required. Name of the ClientTlsPolicy resource. It matches + the pattern + ``projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}`` + description (str): + Optional. Free-text description of the + resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + labels (MutableMapping[str, str]): + Optional. Set of label tags associated with + the resource. + sni (str): + Optional. Server Name Indication string to + present to the server during TLS handshake. E.g: + "secure.example.com". + client_certificate (google.cloud.network_security_v1alpha1.types.CertificateProvider): + Optional. Defines a mechanism to provision + client identity (public and private keys) for + peer to peer authentication. The presence of + this dictates mTLS. + server_validation_ca (MutableSequence[google.cloud.network_security_v1alpha1.types.ValidationCA]): + Optional. Defines the mechanism to obtain the + Certificate Authority certificate to validate + the server certificate. If empty, client does + not validate the server certificate. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + sni: str = proto.Field( + proto.STRING, + number=6, + ) + client_certificate: tls.CertificateProvider = proto.Field( + proto.MESSAGE, + number=7, + message=tls.CertificateProvider, + ) + server_validation_ca: MutableSequence[tls.ValidationCA] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=tls.ValidationCA, + ) + + +class ListClientTlsPoliciesRequest(proto.Message): + r"""Request used by the ListClientTlsPolicies method. + + Attributes: + parent (str): + Required. The project and location from which the + ClientTlsPolicies should be listed, specified in the format + ``projects/*/locations/{location}``. + page_size (int): + Maximum number of ClientTlsPolicies to return + per call. + page_token (str): + The value returned by the last + ``ListClientTlsPoliciesResponse`` Indicates that this is a + continuation of a prior ``ListClientTlsPolicies`` call, and + that the system should return the next page of data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListClientTlsPoliciesResponse(proto.Message): + r"""Response returned by the ListClientTlsPolicies method. + + Attributes: + client_tls_policies (MutableSequence[google.cloud.network_security_v1alpha1.types.ClientTlsPolicy]): + List of ClientTlsPolicy resources. + next_page_token (str): + If there might be 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 + + client_tls_policies: MutableSequence['ClientTlsPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ClientTlsPolicy', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetClientTlsPolicyRequest(proto.Message): + r"""Request used by the GetClientTlsPolicy method. + + Attributes: + name (str): + Required. A name of the ClientTlsPolicy to get. Must be in + the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateClientTlsPolicyRequest(proto.Message): + r"""Request used by the CreateClientTlsPolicy method. + + Attributes: + parent (str): + Required. The parent resource of the ClientTlsPolicy. Must + be in the format ``projects/*/locations/{location}``. + client_tls_policy_id (str): + Required. Short name of the ClientTlsPolicy resource to be + created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and underscores, + and should not start with a number. E.g. + "client_mtls_policy". + client_tls_policy (google.cloud.network_security_v1alpha1.types.ClientTlsPolicy): + Required. ClientTlsPolicy resource to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + client_tls_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + client_tls_policy: 'ClientTlsPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='ClientTlsPolicy', + ) + + +class UpdateClientTlsPolicyRequest(proto.Message): + r"""Request used by UpdateClientTlsPolicy method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ClientTlsPolicy resource by the update. + The fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + client_tls_policy (google.cloud.network_security_v1alpha1.types.ClientTlsPolicy): + Required. Updated ClientTlsPolicy resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + client_tls_policy: 'ClientTlsPolicy' = proto.Field( + proto.MESSAGE, + number=2, + message='ClientTlsPolicy', + ) + + +class DeleteClientTlsPolicyRequest(proto.Message): + r"""Request used by the DeleteClientTlsPolicy method. + + Attributes: + name (str): + Required. A name of the ClientTlsPolicy to delete. Must be + in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/common.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/common.py new file mode 100644 index 000000000000..8511c4469a9f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/common.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1alpha1', + manifest={ + 'OperationMetadata', + }, +) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have [Operation.error][] value + with a [google.rpc.Status.code][google.rpc.Status.code] of + 1, corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/network_security.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/network_security.py new file mode 100644 index 000000000000..f56d6b15fda0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/network_security.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1alpha1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/tls.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/tls.py new file mode 100644 index 000000000000..6474b41a2442 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/tls.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1alpha1', + manifest={ + 'GrpcEndpoint', + 'ValidationCA', + 'CertificateProviderInstance', + 'CertificateProvider', + }, +) + + +class GrpcEndpoint(proto.Message): + r"""Specification of the GRPC Endpoint. + + Attributes: + target_uri (str): + Required. The target URI of the gRPC + endpoint. Only UDS path is supported, and should + start with "unix:". + """ + + target_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ValidationCA(proto.Message): + r"""Specification of ValidationCA. Defines the mechanism to + obtain the Certificate Authority certificate to validate the + peer certificate. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + ca_cert_path (str): + The path to the file holding the CA + certificate to validate the client or server + certificate. + + This field is a member of `oneof`_ ``type``. + grpc_endpoint (google.cloud.network_security_v1alpha1.types.GrpcEndpoint): + gRPC specific configuration to access the + gRPC server to obtain the CA certificate. + + This field is a member of `oneof`_ ``type``. + certificate_provider_instance (google.cloud.network_security_v1alpha1.types.CertificateProviderInstance): + The certificate provider instance + specification that will be passed to the data + plane, which will be used to load necessary + credential information. + + This field is a member of `oneof`_ ``type``. + """ + + ca_cert_path: str = proto.Field( + proto.STRING, + number=1, + oneof='type', + ) + grpc_endpoint: 'GrpcEndpoint' = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message='GrpcEndpoint', + ) + certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( + proto.MESSAGE, + number=3, + oneof='type', + message='CertificateProviderInstance', + ) + + +class CertificateProviderInstance(proto.Message): + r"""Specification of a TLS certificate provider instance. + Workloads may have one or more CertificateProvider instances + (plugins) and one of them is enabled and configured by + specifying this message. Workloads use the values from this + message to locate and load the CertificateProvider instance + configuration. + + Attributes: + plugin_instance (str): + Required. Plugin instance name, used to locate and load + CertificateProvider instance configuration. Set to + "google_cloud_private_spiffe" to use Certificate Authority + Service certificate provider instance. + """ + + plugin_instance: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CertificateProvider(proto.Message): + r"""Specification of certificate provider. Defines the mechanism + to obtain the certificate and private key for peer to peer + authentication. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + local_filepath (google.cloud.network_security_v1alpha1.types.CertificateProvider.TlsCertificateFiles): + Obtain certificates and private key from a + locally mounted filesystem path. + + This field is a member of `oneof`_ ``type``. + grpc_endpoint (google.cloud.network_security_v1alpha1.types.GrpcEndpoint): + gRPC specific configuration to access the + gRPC server to obtain the cert and private key. + + This field is a member of `oneof`_ ``type``. + certificate_provider_instance (google.cloud.network_security_v1alpha1.types.CertificateProviderInstance): + The certificate provider instance + specification that will be passed to the data + plane, which will be used to load necessary + credential information. + + This field is a member of `oneof`_ ``type``. + """ + + class TlsCertificateFiles(proto.Message): + r"""Specification of TLS certificate files. + + Attributes: + certificate_path (str): + Required. The path to the file that has the + certificate containing public key. + private_key_path (str): + Required. The path to the file that has the + private key. + """ + + certificate_path: str = proto.Field( + proto.STRING, + number=1, + ) + private_key_path: str = proto.Field( + proto.STRING, + number=2, + ) + + local_filepath: TlsCertificateFiles = proto.Field( + proto.MESSAGE, + number=1, + oneof='type', + message=TlsCertificateFiles, + ) + grpc_endpoint: 'GrpcEndpoint' = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message='GrpcEndpoint', + ) + certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( + proto.MESSAGE, + number=3, + oneof='type', + message='CertificateProviderInstance', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/mypy.ini b/owl-bot-staging/google-cloud-network-security/v1alpha1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/noxfile.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/noxfile.py new file mode 100644 index 000000000000..6de174fa4528 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/noxfile.py @@ -0,0 +1,592 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re +import shutil + +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = "google-cloud-network-security" + +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy + "mypy<1.16.0", + "types-requests", + "types-protobuf", + ) + session.install(".") + session.run( + "mypy", + "-p", + "google", + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "update", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "check", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("setuptools", "docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def unit(session, protobuf_implementation): + # Install all test dependencies, then install this package in-place. + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # TODO(https://github.com/googleapis/synthtool/issues/1976): + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +def install_systemtest_dependencies(session, *constraints): + session.install("--pre", "grpcio") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python="3.10") +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.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", ""), + ) + + +@nox.session(python="3.10") +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def prerelease_deps(session, protobuf_implementation): + """ + Run all tests with pre-release versions of dependencies installed + rather than the standard non pre-release versions. + Pre-release versions can be installed using + `pip install --pre `. + """ + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # Note: If a dependency is added to the `prerel_deps` list, + # the `core_dependencies_from_source` list in the `core_deps_from_source` + # nox session should also be updated. + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpc-google-iam-v1", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--ignore-installed", dep) + # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` + # to the dictionary below once this bug is fixed. + # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add + # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below + # once this bug is fixed. + package_namespaces = { + "google-api-core": "google.api_core", + "google-auth": "google.auth", + "grpcio": "grpc", + "protobuf": "google.protobuf", + "proto-plus": "proto", + } + + version_namespace = package_namespaces.get(dep) + + print(f"Installed {dep}") + if version_namespace: + session.run( + "python", + "-c", + f"import {version_namespace}; print({version_namespace}.__version__)", + ) + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb"], +) +def core_deps_from_source(session, protobuf_implementation): + """Run all tests with core dependencies installed from source + rather than pulling the dependencies from PyPI. + """ + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and + # `grpcio-status` should be added to the list below so that they are installed from source, + # rather than PyPI. + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be + # added to the list below so that it is installed from source, rather than PyPI + # Note: If a dependency is added to the `core_dependencies_from_source` list, + # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. + core_dependencies_from_source = [ + "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", + "google-api-core @ git+https://github.com/googleapis/python-api-core.git", + "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", + "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", + "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", + ] + + for dep in core_dependencies_from_source: + session.install(dep, "--no-deps", "--ignore-installed") + print(f"Installed {dep}") + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py new file mode 100644 index 000000000000..ed74639eafa8 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1alpha1 + + +async def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1alpha1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py new file mode 100644 index 000000000000..f8438c277bf7 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1alpha1 + + +def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1alpha1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py new file mode 100644 index 000000000000..79acd6b66664 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1alpha1 + + +async def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py new file mode 100644 index 000000000000..55c9008c67f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1alpha1 + + +def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py new file mode 100644 index 000000000000..1158ddae26f5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1alpha1 + + +async def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py new file mode 100644 index 000000000000..3ac60ffd0faa --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1alpha1 + + +def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py new file mode 100644 index 000000000000..2d8699a86d01 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClientTlsPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1alpha1 + + +async def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py new file mode 100644 index 000000000000..4f77a060b847 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClientTlsPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1alpha1 + + +def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1alpha1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py new file mode 100644 index 000000000000..5a8ac0025c38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1alpha1 + + +async def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1alpha1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py new file mode 100644 index 000000000000..4bac529ce6ae --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1alpha1 + + +def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1alpha1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1alpha1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json new file mode 100644 index 000000000000..aca64a760d12 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json @@ -0,0 +1,844 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.networksecurity.v1alpha1", + "version": "v1alpha1" + } + ], + "language": "PYTHON", + "name": "google-cloud-network-security", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient.create_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.CreateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1alpha1.types.CreateClientTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy" + }, + { + "name": "client_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_client_tls_policy" + }, + "description": "Sample for CreateClientTlsPolicy", + "file": "networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient.create_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.CreateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1alpha1.types.CreateClientTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy" + }, + { + "name": "client_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_client_tls_policy" + }, + "description": "Sample for CreateClientTlsPolicy", + "file": "networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient.delete_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.DeleteClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1alpha1.types.DeleteClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_client_tls_policy" + }, + "description": "Sample for DeleteClientTlsPolicy", + "file": "networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient.delete_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.DeleteClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1alpha1.types.DeleteClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_client_tls_policy" + }, + "description": "Sample for DeleteClientTlsPolicy", + "file": "networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient.get_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.GetClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1alpha1.types.GetClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy", + "shortName": "get_client_tls_policy" + }, + "description": "Sample for GetClientTlsPolicy", + "file": "networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient.get_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.GetClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1alpha1.types.GetClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy", + "shortName": "get_client_tls_policy" + }, + "description": "Sample for GetClientTlsPolicy", + "file": "networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient.list_client_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.ListClientTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListClientTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1alpha1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager", + "shortName": "list_client_tls_policies" + }, + "description": "Sample for ListClientTlsPolicies", + "file": "networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient.list_client_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.ListClientTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListClientTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1alpha1.services.network_security.pagers.ListClientTlsPoliciesPager", + "shortName": "list_client_tls_policies" + }, + "description": "Sample for ListClientTlsPolicies", + "file": "networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient.update_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.UpdateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1alpha1.types.UpdateClientTlsPolicyRequest" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_client_tls_policy" + }, + "description": "Sample for UpdateClientTlsPolicy", + "file": "networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient.update_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.UpdateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1alpha1.types.UpdateClientTlsPolicyRequest" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_client_tls_policy" + }, + "description": "Sample for UpdateClientTlsPolicy", + "file": "networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/scripts/fixup_network_security_v1alpha1_keywords.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/scripts/fixup_network_security_v1alpha1_keywords.py new file mode 100644 index 000000000000..f2a9d62fb02b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/scripts/fixup_network_security_v1alpha1_keywords.py @@ -0,0 +1,180 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 network_securityCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_client_tls_policy': ('parent', 'client_tls_policy_id', 'client_tls_policy', ), + 'delete_client_tls_policy': ('name', ), + 'get_client_tls_policy': ('name', ), + 'list_client_tls_policies': ('parent', 'page_size', 'page_token', ), + 'update_client_tls_policy': ('client_tls_policy', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=network_securityCallTransformer(), +): + """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 network_security 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/google-cloud-network-security/v1alpha1/setup.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/setup.py new file mode 100644 index 000000000000..1f618aa7ad2f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-network-security' + + +description = "Google Cloud Network Security API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/network_security/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0", + "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", + "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.14.0, <1.0.0", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2010e549cceb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.13.txt @@ -0,0 +1,12 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +proto-plus>=1 +protobuf>=6 +grpc-google-iam-v1>=0 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..56affbd9bd75 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +grpc-google-iam-v1==0.14.0 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1alpha1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1alpha1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/test_network_security.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/test_network_security.py new file mode 100644 index 000000000000..3ac7a18a5f2f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/test_network_security.py @@ -0,0 +1,7023 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.network_security_v1alpha1.services.network_security import NetworkSecurityAsyncClient +from google.cloud.network_security_v1alpha1.services.network_security import NetworkSecurityClient +from google.cloud.network_security_v1alpha1.services.network_security import pagers +from google.cloud.network_security_v1alpha1.services.network_security import transports +from google.cloud.network_security_v1alpha1.types import client_tls_policy +from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1alpha1.types import common +from google.cloud.network_security_v1alpha1.types import tls +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# 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 + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 NetworkSecurityClient._get_default_mtls_endpoint(None) is None + assert NetworkSecurityClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert NetworkSecurityClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + NetworkSecurityClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + NetworkSecurityClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert NetworkSecurityClient._get_client_cert_source(None, False) is None + assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert NetworkSecurityClient._get_client_cert_source(None, True) is mock_default_cert_source + assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE + default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert NetworkSecurityClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + assert NetworkSecurityClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert NetworkSecurityClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert NetworkSecurityClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert NetworkSecurityClient._get_universe_domain(None, None) == NetworkSecurityClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + NetworkSecurityClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = NetworkSecurityClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = NetworkSecurityClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (NetworkSecurityClient, "grpc"), + (NetworkSecurityAsyncClient, "grpc_asyncio"), + (NetworkSecurityClient, "rest"), +]) +def test_network_security_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networksecurity.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.NetworkSecurityGrpcTransport, "grpc"), + (transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.NetworkSecurityRestTransport, "rest"), +]) +def test_network_security_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (NetworkSecurityClient, "grpc"), + (NetworkSecurityAsyncClient, "grpc_asyncio"), + (NetworkSecurityClient, "rest"), +]) +def test_network_security_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://networksecurity.googleapis.com' + ) + + +def test_network_security_client_get_transport_class(): + transport = NetworkSecurityClient.get_transport_class() + available_transports = [ + transports.NetworkSecurityGrpcTransport, + transports.NetworkSecurityRestTransport, + ] + assert transport in available_transports + + transport = NetworkSecurityClient.get_transport_class("grpc") + assert transport == transports.NetworkSecurityGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"), +]) +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +def test_network_security_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(NetworkSecurityClient, '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(NetworkSecurityClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "true"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "false"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", "true"), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", "false"), +]) +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_network_security_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + NetworkSecurityClient, NetworkSecurityAsyncClient +]) +@mock.patch.object(NetworkSecurityClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityAsyncClient)) +def test_network_security_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + NetworkSecurityClient, NetworkSecurityAsyncClient +]) +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +def test_network_security_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE + default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"), +]) +def test_network_security_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", None), +]) +def test_network_security_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_network_security_client_client_options_from_dict(): + with mock.patch('google.cloud.network_security_v1alpha1.services.network_security.transports.NetworkSecurityGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = NetworkSecurityClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_network_security_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networksecurity.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.ListClientTlsPoliciesRequest, + dict, +]) +def test_list_client_tls_policies(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = client_tls_policy.ListClientTlsPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClientTlsPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_client_tls_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = client_tls_policy.ListClientTlsPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_client_tls_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == client_tls_policy.ListClientTlsPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_client_tls_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_client_tls_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_client_tls_policies] = mock_rpc + request = {} + client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_client_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_client_tls_policies in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_client_tls_policies] = mock_rpc + + request = {} + await client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_client_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.ListClientTlsPoliciesRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = client_tls_policy.ListClientTlsPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClientTlsPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async_from_dict(): + await test_list_client_tls_policies_async(request_type=dict) + +def test_list_client_tls_policies_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.ListClientTlsPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + client.list_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_client_tls_policies_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.ListClientTlsPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) + await client.list_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_client_tls_policies_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_client_tls_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_client_tls_policies_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policies( + client_tls_policy.ListClientTlsPoliciesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_client_tls_policies_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_client_tls_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_client_tls_policies_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_client_tls_policies( + client_tls_policy.ListClientTlsPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_client_tls_policies_pager(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_client_tls_policies(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) + for i in results) +def test_list_client_tls_policies_pages(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_client_tls_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_list_client_tls_policies_async_pager(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_client_tls_policies(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async_pages(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_client_tls_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.GetClientTlsPolicyRequest, + dict, +]) +def test_get_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + ) + response = client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = client_tls_policy.GetClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, client_tls_policy.ClientTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.sni == 'sni_value' + + +def test_get_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = client_tls_policy.GetClientTlsPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == client_tls_policy.GetClientTlsPolicyRequest( + name='name_value', + ) + +def test_get_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_client_tls_policy] = mock_rpc + request = {} + client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_client_tls_policy] = mock_rpc + + request = {} + await client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.GetClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + )) + response = await client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = client_tls_policy.GetClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, client_tls_policy.ClientTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.sni == 'sni_value' + + +@pytest.mark.asyncio +async def test_get_client_tls_policy_async_from_dict(): + await test_get_client_tls_policy_async(request_type=dict) + +def test_get_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.GetClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value = client_tls_policy.ClientTlsPolicy() + client.get_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.GetClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) + await client.get_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ClientTlsPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + client_tls_policy.GetClientTlsPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ClientTlsPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_client_tls_policy( + client_tls_policy.GetClientTlsPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_client_tls_policy.CreateClientTlsPolicyRequest, + dict, +]) +def test_create_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest( + parent='parent_value', + client_tls_policy_id='client_tls_policy_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_client_tls_policy.CreateClientTlsPolicyRequest( + parent='parent_value', + client_tls_policy_id='client_tls_policy_id_value', + ) + +def test_create_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_client_tls_policy] = mock_rpc + request = {} + client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_client_tls_policy] = mock_rpc + + request = {} + await client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_client_tls_policy_async_from_dict(): + await test_create_client_tls_policy_async(request_type=dict) + +def test_create_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_client_tls_policy( + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].client_tls_policy_id + mock_val = 'client_tls_policy_id_value' + assert arg == mock_val + + +def test_create_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + gcn_client_tls_policy.CreateClientTlsPolicyRequest(), + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + +@pytest.mark.asyncio +async def test_create_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_client_tls_policy( + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].client_tls_policy_id + mock_val = 'client_tls_policy_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_client_tls_policy( + gcn_client_tls_policy.CreateClientTlsPolicyRequest(), + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_client_tls_policy.UpdateClientTlsPolicyRequest, + dict, +]) +def test_update_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_client_tls_policy.UpdateClientTlsPolicyRequest( + ) + +def test_update_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_client_tls_policy] = mock_rpc + request = {} + client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_client_tls_policy] = mock_rpc + + request = {} + await client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_client_tls_policy_async_from_dict(): + await test_update_client_tls_policy_async(request_type=dict) + +def test_update_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + request.client_tls_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_client_tls_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', + 'client_tls_policy.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + request.client_tls_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_client_tls_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', + 'client_tls_policy.name=name_value', + ) in kw['metadata'] + + +def test_update_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_client_tls_policy( + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_client_tls_policy( + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_client_tls_policy( + gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.DeleteClientTlsPolicyRequest, + dict, +]) +def test_delete_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = client_tls_policy.DeleteClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = client_tls_policy.DeleteClientTlsPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == client_tls_policy.DeleteClientTlsPolicyRequest( + name='name_value', + ) + +def test_delete_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_client_tls_policy] = mock_rpc + request = {} + client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_client_tls_policy] = mock_rpc + + request = {} + await client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.DeleteClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = client_tls_policy.DeleteClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_async_from_dict(): + await test_delete_client_tls_policy_async(request_type=dict) + +def test_delete_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.DeleteClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.DeleteClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + client_tls_policy.DeleteClientTlsPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_client_tls_policy( + client_tls_policy.DeleteClientTlsPolicyRequest(), + name='name_value', + ) + + +def test_list_client_tls_policies_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_client_tls_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_client_tls_policies] = mock_rpc + + request = {} + client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_client_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_client_tls_policies_rest_required_fields(request_type=client_tls_policy.ListClientTlsPoliciesRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_client_tls_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_client_tls_policies._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ListClientTlsPoliciesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_client_tls_policies(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_client_tls_policies_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_client_tls_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_client_tls_policies_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ListClientTlsPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_client_tls_policies(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/clientTlsPolicies" % client.transport._host, args[1]) + + +def test_list_client_tls_policies_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_client_tls_policies( + client_tls_policy.ListClientTlsPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_client_tls_policies_rest_pager(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(client_tls_policy.ListClientTlsPoliciesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_client_tls_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) + for i in results) + + pages = list(client.list_client_tls_policies(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_client_tls_policy] = mock_rpc + + request = {} + client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_client_tls_policy_rest_required_fields(request_type=client_tls_policy.GetClientTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ClientTlsPolicy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_client_tls_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ClientTlsPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_client_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) + + +def test_get_client_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_client_tls_policy( + client_tls_policy.GetClientTlsPolicyRequest(), + name='name_value', + ) + + +def test_create_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_client_tls_policy] = mock_rpc + + request = {} + client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_client_tls_policy_rest_required_fields(request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["client_tls_policy_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "clientTlsPolicyId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clientTlsPolicyId" in jsonified_request + assert jsonified_request["clientTlsPolicyId"] == request_init["client_tls_policy_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["clientTlsPolicyId"] = 'client_tls_policy_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_client_tls_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("client_tls_policy_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "clientTlsPolicyId" in jsonified_request + assert jsonified_request["clientTlsPolicyId"] == 'client_tls_policy_id_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_client_tls_policy(request) + + expected_params = [ + ( + "clientTlsPolicyId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("clientTlsPolicyId", )) & set(("parent", "clientTlsPolicyId", "clientTlsPolicy", ))) + + +def test_create_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_client_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/clientTlsPolicies" % client.transport._host, args[1]) + + +def test_create_client_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_client_tls_policy( + gcn_client_tls_policy.CreateClientTlsPolicyRequest(), + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + +def test_update_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_client_tls_policy] = mock_rpc + + request = {} + client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_client_tls_policy_rest_required_fields(request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_client_tls_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_client_tls_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("clientTlsPolicy", ))) + + +def test_update_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_client_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) + + +def test_update_client_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_client_tls_policy( + gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_client_tls_policy_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_client_tls_policy] = mock_rpc + + request = {} + client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_client_tls_policy_rest_required_fields(request_type=client_tls_policy.DeleteClientTlsPolicyRequest): + transport_class = transports.NetworkSecurityRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_client_tls_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_client_tls_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_client_tls_policy_rest_unset_required_fields(): + transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_client_tls_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_client_tls_policy_rest_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_client_tls_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) + + +def test_delete_client_tls_policy_rest_flattened_error(transport: str = 'rest'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_client_tls_policy( + client_tls_policy.DeleteClientTlsPolicyRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = NetworkSecurityClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.NetworkSecurityGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.NetworkSecurityGrpcTransport, + transports.NetworkSecurityGrpcAsyncIOTransport, + transports.NetworkSecurityRestTransport, +]) +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_kind_grpc(): + transport = NetworkSecurityClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_client_tls_policies_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + client.list_client_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.ListClientTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value = client_tls_policy.ClientTlsPolicy() + client.get_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.GetClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = NetworkSecurityAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_client_tls_policies_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + )) + await client.list_client_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.ListClientTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + )) + await client.get_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.GetClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = NetworkSecurityClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_client_tls_policies_rest_bad_request(request_type=client_tls_policy.ListClientTlsPoliciesRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_client_tls_policies(request) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.ListClientTlsPoliciesRequest, + dict, +]) +def test_list_client_tls_policies_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_client_tls_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClientTlsPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_client_tls_policies_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_client_tls_policies") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_client_tls_policies_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_list_client_tls_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = client_tls_policy.ListClientTlsPoliciesRequest.pb(client_tls_policy.ListClientTlsPoliciesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = client_tls_policy.ListClientTlsPoliciesResponse.to_json(client_tls_policy.ListClientTlsPoliciesResponse()) + req.return_value.content = return_value + + request = client_tls_policy.ListClientTlsPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + post_with_metadata.return_value = client_tls_policy.ListClientTlsPoliciesResponse(), metadata + + client.list_client_tls_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_client_tls_policy_rest_bad_request(request_type=client_tls_policy.GetClientTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_client_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.GetClientTlsPolicyRequest, + dict, +]) +def test_get_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_client_tls_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, client_tls_policy.ClientTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.sni == 'sni_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_client_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_client_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_get_client_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = client_tls_policy.GetClientTlsPolicyRequest.pb(client_tls_policy.GetClientTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = client_tls_policy.ClientTlsPolicy.to_json(client_tls_policy.ClientTlsPolicy()) + req.return_value.content = return_value + + request = client_tls_policy.GetClientTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = client_tls_policy.ClientTlsPolicy() + post_with_metadata.return_value = client_tls_policy.ClientTlsPolicy(), metadata + + client.get_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_client_tls_policy_rest_bad_request(request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_client_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_client_tls_policy.CreateClientTlsPolicyRequest, + dict, +]) +def test_create_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["client_tls_policy"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'sni': 'sni_value', 'client_certificate': {'local_filepath': {'certificate_path': 'certificate_path_value', 'private_key_path': 'private_key_path_value'}, 'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'server_validation_ca': [{'ca_cert_path': 'ca_cert_path_value', 'grpc_endpoint': {}, 'certificate_provider_instance': {}}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_client_tls_policy.CreateClientTlsPolicyRequest.meta.fields["client_tls_policy"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["client_tls_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["client_tls_policy"][field])): + del request_init["client_tls_policy"][field][i][subfield] + else: + del request_init["client_tls_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_client_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_client_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_client_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_create_client_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(gcn_client_tls_policy.CreateClientTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_client_tls_policy_rest_bad_request(request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_client_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gcn_client_tls_policy.UpdateClientTlsPolicyRequest, + dict, +]) +def test_update_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} + request_init["client_tls_policy"] = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'sni': 'sni_value', 'client_certificate': {'local_filepath': {'certificate_path': 'certificate_path_value', 'private_key_path': 'private_key_path_value'}, 'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'server_validation_ca': [{'ca_cert_path': 'ca_cert_path_value', 'grpc_endpoint': {}, 'certificate_provider_instance': {}}]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.meta.fields["client_tls_policy"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["client_tls_policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["client_tls_policy"][field])): + del request_init["client_tls_policy"][field][i][subfield] + else: + del request_init["client_tls_policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_client_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_client_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_client_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_update_client_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(gcn_client_tls_policy.UpdateClientTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_client_tls_policy_rest_bad_request(request_type=client_tls_policy.DeleteClientTlsPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_client_tls_policy(request) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.DeleteClientTlsPolicyRequest, + dict, +]) +def test_delete_client_tls_policy_rest_call_success(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_client_tls_policy(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_client_tls_policy_rest_interceptors(null_interceptor): + transport = transports.NetworkSecurityRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), + ) + client = NetworkSecurityClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_client_tls_policy") as post, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_client_tls_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_delete_client_tls_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = client_tls_policy.DeleteClientTlsPolicyRequest.pb(client_tls_policy.DeleteClientTlsPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = client_tls_policy.DeleteClientTlsPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = '{}' + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_initialize_client_w_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_client_tls_policies_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + client.list_client_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.ListClientTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + client.get_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.GetClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + client.create_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + client.update_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_client_tls_policy_empty_call_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + client.delete_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() + + assert args[0] == request_msg + + +def test_network_security_rest_lro_client(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, +operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.NetworkSecurityGrpcTransport, + ) + +def test_network_security_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.NetworkSecurityTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_network_security_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.network_security_v1alpha1.services.network_security.transports.NetworkSecurityTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.NetworkSecurityTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_client_tls_policies', + 'get_client_tls_policy', + 'create_client_tls_policy', + 'update_client_tls_policy', + 'delete_client_tls_policy', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_network_security_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.network_security_v1alpha1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkSecurityTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_network_security_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.network_security_v1alpha1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkSecurityTransport() + adc.assert_called_once() + + +def test_network_security_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) + NetworkSecurityClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkSecurityGrpcTransport, + transports.NetworkSecurityGrpcAsyncIOTransport, + ], +) +def test_network_security_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.NetworkSecurityGrpcTransport, + transports.NetworkSecurityGrpcAsyncIOTransport, + transports.NetworkSecurityRestTransport, + ], +) +def test_network_security_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.NetworkSecurityGrpcTransport, grpc_helpers), + (transports.NetworkSecurityGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_network_security_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( + "networksecurity.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="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) +def test_network_security_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_network_security_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.NetworkSecurityRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_network_security_host_no_port(transport_name): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networksecurity.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_network_security_host_with_port(transport_name): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networksecurity.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://networksecurity.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_network_security_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = NetworkSecurityClient( + credentials=creds1, + transport=transport_name, + ) + client2 = NetworkSecurityClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_client_tls_policies._session + session2 = client2.transport.list_client_tls_policies._session + assert session1 != session2 + session1 = client1.transport.get_client_tls_policy._session + session2 = client2.transport.get_client_tls_policy._session + assert session1 != session2 + session1 = client1.transport.create_client_tls_policy._session + session2 = client2.transport.create_client_tls_policy._session + assert session1 != session2 + session1 = client1.transport.update_client_tls_policy._session + session2 = client2.transport.update_client_tls_policy._session + assert session1 != session2 + session1 = client1.transport.delete_client_tls_policy._session + session2 = client2.transport.delete_client_tls_policy._session + assert session1 != session2 +def test_network_security_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NetworkSecurityGrpcTransport( + 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_network_security_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NetworkSecurityGrpcAsyncIOTransport( + 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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) +def test_network_security_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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) +def test_network_security_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_network_security_grpc_lro_client(): + client = NetworkSecurityClient( + 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_network_security_grpc_lro_async_client(): + client = NetworkSecurityAsyncClient( + 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_client_tls_policy_path(): + project = "squid" + location = "clam" + client_tls_policy = "whelk" + expected = "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) + actual = NetworkSecurityClient.client_tls_policy_path(project, location, client_tls_policy) + assert expected == actual + + +def test_parse_client_tls_policy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "client_tls_policy": "nudibranch", + } + path = NetworkSecurityClient.client_tls_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_client_tls_policy_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = NetworkSecurityClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = NetworkSecurityClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = NetworkSecurityClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = NetworkSecurityClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = NetworkSecurityClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = NetworkSecurityClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = NetworkSecurityClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = NetworkSecurityClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = NetworkSecurityClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = NetworkSecurityClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: + transport_class = NetworkSecurityClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/.coveragerc b/owl-bot-staging/google-cloud-network-security/v1beta1/.coveragerc new file mode 100644 index 000000000000..ed01d62f0f9a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/network_security/__init__.py + google/cloud/network_security/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/.flake8 b/owl-bot-staging/google-cloud-network-security/v1beta1/.flake8 new file mode 100644 index 000000000000..90316de21489 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/.flake8 @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +[flake8] +# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): +# Resolve flake8 lint issues +ignore = E203, E231, E266, E501, W503 +exclude = + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): + # Ensure that generated code passes flake8 lint + **/gapic/** + **/services/** + **/types/** + # Exclude Protobuf gencode + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/LICENSE b/owl-bot-staging/google-cloud-network-security/v1beta1/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT 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/google-cloud-network-security/v1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-network-security/v1beta1/MANIFEST.in new file mode 100644 index 000000000000..dae249ec8976 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/MANIFEST.in @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +include README.rst LICENSE +recursive-include google *.py *.pyi *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/README.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/README.rst new file mode 100644 index 000000000000..fed4f0a4d3c6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Cloud Network Security 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 Network Security 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 + + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + + +Examples +^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + + +Examples +^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_templates/layout.html b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_templates/layout.html new file mode 100644 index 000000000000..95e9c77fcfe1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/conf.py b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/conf.py new file mode 100644 index 000000000000..cf26b0443b74 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/conf.py @@ -0,0 +1,385 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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-network-security 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("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.5.0" + +# 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.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-network-security" +copyright = u"2025, Google, LLC" +author = u"Google APIs" + +# 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", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# 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 google-cloud-network-security", + "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-network-security-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-network-security.tex", + u"google-cloud-network-security Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-network-security", + "google-cloud-network-security Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-network-security", + "google-cloud-network-security Documentation", + author, + "google-cloud-network-security", + "google-cloud-network-security Library", + "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": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", 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/google-cloud-network-security/v1beta1/docs/index.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/index.rst new file mode 100644 index 000000000000..887a96a98d64 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/index.rst @@ -0,0 +1,10 @@ +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + network_security_v1beta1/services_ + network_security_v1beta1/types_ diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/multiprocessing.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/network_security.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/network_security.rst new file mode 100644 index 000000000000..d410f02fae7f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/network_security.rst @@ -0,0 +1,10 @@ +NetworkSecurity +--------------------------------- + +.. automodule:: google.cloud.network_security_v1beta1.services.network_security + :members: + :inherited-members: + +.. automodule:: google.cloud.network_security_v1beta1.services.network_security.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/services_.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/services_.rst new file mode 100644 index 000000000000..dd4dc6164423 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Network Security v1beta1 API +====================================================== +.. toctree:: + :maxdepth: 2 + + network_security diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/types_.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/types_.rst new file mode 100644 index 000000000000..a51fb755cd14 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Network Security v1beta1 API +=================================================== + +.. automodule:: google.cloud.network_security_v1beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/__init__.py new file mode 100644 index 000000000000..69ca4223fb8a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/__init__.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.network_security import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.network_security_v1beta1.services.network_security.client import NetworkSecurityClient +from google.cloud.network_security_v1beta1.services.network_security.async_client import NetworkSecurityAsyncClient + +from google.cloud.network_security_v1beta1.types.authorization_policy import AuthorizationPolicy +from google.cloud.network_security_v1beta1.types.authorization_policy import CreateAuthorizationPolicyRequest +from google.cloud.network_security_v1beta1.types.authorization_policy import DeleteAuthorizationPolicyRequest +from google.cloud.network_security_v1beta1.types.authorization_policy import GetAuthorizationPolicyRequest +from google.cloud.network_security_v1beta1.types.authorization_policy import ListAuthorizationPoliciesRequest +from google.cloud.network_security_v1beta1.types.authorization_policy import ListAuthorizationPoliciesResponse +from google.cloud.network_security_v1beta1.types.authorization_policy import UpdateAuthorizationPolicyRequest +from google.cloud.network_security_v1beta1.types.client_tls_policy import ClientTlsPolicy +from google.cloud.network_security_v1beta1.types.client_tls_policy import CreateClientTlsPolicyRequest +from google.cloud.network_security_v1beta1.types.client_tls_policy import DeleteClientTlsPolicyRequest +from google.cloud.network_security_v1beta1.types.client_tls_policy import GetClientTlsPolicyRequest +from google.cloud.network_security_v1beta1.types.client_tls_policy import ListClientTlsPoliciesRequest +from google.cloud.network_security_v1beta1.types.client_tls_policy import ListClientTlsPoliciesResponse +from google.cloud.network_security_v1beta1.types.client_tls_policy import UpdateClientTlsPolicyRequest +from google.cloud.network_security_v1beta1.types.common import OperationMetadata +from google.cloud.network_security_v1beta1.types.server_tls_policy import CreateServerTlsPolicyRequest +from google.cloud.network_security_v1beta1.types.server_tls_policy import DeleteServerTlsPolicyRequest +from google.cloud.network_security_v1beta1.types.server_tls_policy import GetServerTlsPolicyRequest +from google.cloud.network_security_v1beta1.types.server_tls_policy import ListServerTlsPoliciesRequest +from google.cloud.network_security_v1beta1.types.server_tls_policy import ListServerTlsPoliciesResponse +from google.cloud.network_security_v1beta1.types.server_tls_policy import ServerTlsPolicy +from google.cloud.network_security_v1beta1.types.server_tls_policy import UpdateServerTlsPolicyRequest +from google.cloud.network_security_v1beta1.types.tls import CertificateProvider +from google.cloud.network_security_v1beta1.types.tls import CertificateProviderInstance +from google.cloud.network_security_v1beta1.types.tls import GrpcEndpoint +from google.cloud.network_security_v1beta1.types.tls import ValidationCA + +__all__ = ('NetworkSecurityClient', + 'NetworkSecurityAsyncClient', + 'AuthorizationPolicy', + 'CreateAuthorizationPolicyRequest', + 'DeleteAuthorizationPolicyRequest', + 'GetAuthorizationPolicyRequest', + 'ListAuthorizationPoliciesRequest', + 'ListAuthorizationPoliciesResponse', + 'UpdateAuthorizationPolicyRequest', + 'ClientTlsPolicy', + 'CreateClientTlsPolicyRequest', + 'DeleteClientTlsPolicyRequest', + 'GetClientTlsPolicyRequest', + 'ListClientTlsPoliciesRequest', + 'ListClientTlsPoliciesResponse', + 'UpdateClientTlsPolicyRequest', + 'OperationMetadata', + 'CreateServerTlsPolicyRequest', + 'DeleteServerTlsPolicyRequest', + 'GetServerTlsPolicyRequest', + 'ListServerTlsPoliciesRequest', + 'ListServerTlsPoliciesResponse', + 'ServerTlsPolicy', + 'UpdateServerTlsPolicyRequest', + 'CertificateProvider', + 'CertificateProviderInstance', + 'GrpcEndpoint', + 'ValidationCA', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/py.typed b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/py.typed new file mode 100644 index 000000000000..41b3c3019247 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/__init__.py new file mode 100644 index 000000000000..095f44249d17 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.network_security_v1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.network_security import NetworkSecurityClient +from .services.network_security import NetworkSecurityAsyncClient + +from .types.authorization_policy import AuthorizationPolicy +from .types.authorization_policy import CreateAuthorizationPolicyRequest +from .types.authorization_policy import DeleteAuthorizationPolicyRequest +from .types.authorization_policy import GetAuthorizationPolicyRequest +from .types.authorization_policy import ListAuthorizationPoliciesRequest +from .types.authorization_policy import ListAuthorizationPoliciesResponse +from .types.authorization_policy import UpdateAuthorizationPolicyRequest +from .types.client_tls_policy import ClientTlsPolicy +from .types.client_tls_policy import CreateClientTlsPolicyRequest +from .types.client_tls_policy import DeleteClientTlsPolicyRequest +from .types.client_tls_policy import GetClientTlsPolicyRequest +from .types.client_tls_policy import ListClientTlsPoliciesRequest +from .types.client_tls_policy import ListClientTlsPoliciesResponse +from .types.client_tls_policy import UpdateClientTlsPolicyRequest +from .types.common import OperationMetadata +from .types.server_tls_policy import CreateServerTlsPolicyRequest +from .types.server_tls_policy import DeleteServerTlsPolicyRequest +from .types.server_tls_policy import GetServerTlsPolicyRequest +from .types.server_tls_policy import ListServerTlsPoliciesRequest +from .types.server_tls_policy import ListServerTlsPoliciesResponse +from .types.server_tls_policy import ServerTlsPolicy +from .types.server_tls_policy import UpdateServerTlsPolicyRequest +from .types.tls import CertificateProvider +from .types.tls import CertificateProviderInstance +from .types.tls import GrpcEndpoint +from .types.tls import ValidationCA + +__all__ = ( + 'NetworkSecurityAsyncClient', +'AuthorizationPolicy', +'CertificateProvider', +'CertificateProviderInstance', +'ClientTlsPolicy', +'CreateAuthorizationPolicyRequest', +'CreateClientTlsPolicyRequest', +'CreateServerTlsPolicyRequest', +'DeleteAuthorizationPolicyRequest', +'DeleteClientTlsPolicyRequest', +'DeleteServerTlsPolicyRequest', +'GetAuthorizationPolicyRequest', +'GetClientTlsPolicyRequest', +'GetServerTlsPolicyRequest', +'GrpcEndpoint', +'ListAuthorizationPoliciesRequest', +'ListAuthorizationPoliciesResponse', +'ListClientTlsPoliciesRequest', +'ListClientTlsPoliciesResponse', +'ListServerTlsPoliciesRequest', +'ListServerTlsPoliciesResponse', +'NetworkSecurityClient', +'OperationMetadata', +'ServerTlsPolicy', +'UpdateAuthorizationPolicyRequest', +'UpdateClientTlsPolicyRequest', +'UpdateServerTlsPolicyRequest', +'ValidationCA', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_metadata.json new file mode 100644 index 000000000000..8bf9dacdd358 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_metadata.json @@ -0,0 +1,173 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.network_security_v1beta1", + "protoPackage": "google.cloud.networksecurity.v1beta1", + "schema": "1.0", + "services": { + "NetworkSecurity": { + "clients": { + "grpc": { + "libraryClient": "NetworkSecurityClient", + "rpcs": { + "CreateAuthorizationPolicy": { + "methods": [ + "create_authorization_policy" + ] + }, + "CreateClientTlsPolicy": { + "methods": [ + "create_client_tls_policy" + ] + }, + "CreateServerTlsPolicy": { + "methods": [ + "create_server_tls_policy" + ] + }, + "DeleteAuthorizationPolicy": { + "methods": [ + "delete_authorization_policy" + ] + }, + "DeleteClientTlsPolicy": { + "methods": [ + "delete_client_tls_policy" + ] + }, + "DeleteServerTlsPolicy": { + "methods": [ + "delete_server_tls_policy" + ] + }, + "GetAuthorizationPolicy": { + "methods": [ + "get_authorization_policy" + ] + }, + "GetClientTlsPolicy": { + "methods": [ + "get_client_tls_policy" + ] + }, + "GetServerTlsPolicy": { + "methods": [ + "get_server_tls_policy" + ] + }, + "ListAuthorizationPolicies": { + "methods": [ + "list_authorization_policies" + ] + }, + "ListClientTlsPolicies": { + "methods": [ + "list_client_tls_policies" + ] + }, + "ListServerTlsPolicies": { + "methods": [ + "list_server_tls_policies" + ] + }, + "UpdateAuthorizationPolicy": { + "methods": [ + "update_authorization_policy" + ] + }, + "UpdateClientTlsPolicy": { + "methods": [ + "update_client_tls_policy" + ] + }, + "UpdateServerTlsPolicy": { + "methods": [ + "update_server_tls_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "NetworkSecurityAsyncClient", + "rpcs": { + "CreateAuthorizationPolicy": { + "methods": [ + "create_authorization_policy" + ] + }, + "CreateClientTlsPolicy": { + "methods": [ + "create_client_tls_policy" + ] + }, + "CreateServerTlsPolicy": { + "methods": [ + "create_server_tls_policy" + ] + }, + "DeleteAuthorizationPolicy": { + "methods": [ + "delete_authorization_policy" + ] + }, + "DeleteClientTlsPolicy": { + "methods": [ + "delete_client_tls_policy" + ] + }, + "DeleteServerTlsPolicy": { + "methods": [ + "delete_server_tls_policy" + ] + }, + "GetAuthorizationPolicy": { + "methods": [ + "get_authorization_policy" + ] + }, + "GetClientTlsPolicy": { + "methods": [ + "get_client_tls_policy" + ] + }, + "GetServerTlsPolicy": { + "methods": [ + "get_server_tls_policy" + ] + }, + "ListAuthorizationPolicies": { + "methods": [ + "list_authorization_policies" + ] + }, + "ListClientTlsPolicies": { + "methods": [ + "list_client_tls_policies" + ] + }, + "ListServerTlsPolicies": { + "methods": [ + "list_server_tls_policies" + ] + }, + "UpdateAuthorizationPolicy": { + "methods": [ + "update_authorization_policy" + ] + }, + "UpdateClientTlsPolicy": { + "methods": [ + "update_client_tls_policy" + ] + }, + "UpdateServerTlsPolicy": { + "methods": [ + "update_server_tls_policy" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/py.typed b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/py.typed new file mode 100644 index 000000000000..41b3c3019247 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/__init__.py new file mode 100644 index 000000000000..cddb3cfba9e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 NetworkSecurityClient +from .async_client import NetworkSecurityAsyncClient + +__all__ = ( + 'NetworkSecurityClient', + 'NetworkSecurityAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/async_client.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/async_client.py new file mode 100644 index 000000000000..7098e6dca664 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/async_client.py @@ -0,0 +1,2866 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.network_security_v1beta1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1beta1.services.network_security import pagers +from google.cloud.network_security_v1beta1.types import authorization_policy +from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1beta1.types import common +from google.cloud.network_security_v1beta1.types import server_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy +from google.cloud.network_security_v1beta1.types import tls +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport +from .client import NetworkSecurityClient + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +class NetworkSecurityAsyncClient: + """Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + """ + + _client: NetworkSecurityClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = NetworkSecurityClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = NetworkSecurityClient._DEFAULT_UNIVERSE + + authorization_policy_path = staticmethod(NetworkSecurityClient.authorization_policy_path) + parse_authorization_policy_path = staticmethod(NetworkSecurityClient.parse_authorization_policy_path) + client_tls_policy_path = staticmethod(NetworkSecurityClient.client_tls_policy_path) + parse_client_tls_policy_path = staticmethod(NetworkSecurityClient.parse_client_tls_policy_path) + server_tls_policy_path = staticmethod(NetworkSecurityClient.server_tls_policy_path) + parse_server_tls_policy_path = staticmethod(NetworkSecurityClient.parse_server_tls_policy_path) + common_billing_account_path = staticmethod(NetworkSecurityClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(NetworkSecurityClient.parse_common_billing_account_path) + common_folder_path = staticmethod(NetworkSecurityClient.common_folder_path) + parse_common_folder_path = staticmethod(NetworkSecurityClient.parse_common_folder_path) + common_organization_path = staticmethod(NetworkSecurityClient.common_organization_path) + parse_common_organization_path = staticmethod(NetworkSecurityClient.parse_common_organization_path) + common_project_path = staticmethod(NetworkSecurityClient.common_project_path) + parse_common_project_path = staticmethod(NetworkSecurityClient.parse_common_project_path) + common_location_path = staticmethod(NetworkSecurityClient.common_location_path) + parse_common_location_path = staticmethod(NetworkSecurityClient.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: + NetworkSecurityAsyncClient: The constructed client. + """ + return NetworkSecurityClient.from_service_account_info.__func__(NetworkSecurityAsyncClient, 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: + NetworkSecurityAsyncClient: The constructed client. + """ + return NetworkSecurityClient.from_service_account_file.__func__(NetworkSecurityAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return NetworkSecurityClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> NetworkSecurityTransport: + """Returns the transport used by the client instance. + + Returns: + NetworkSecurityTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = NetworkSecurityClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the network security async 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the NetworkSecurityTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client = NetworkSecurityClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networksecurity_v1beta1.NetworkSecurityAsyncClient`.", + extra = { + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._client._transport, "_credentials") else { + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "credentialsType": None, + } + ) + + async def list_authorization_policies(self, + request: Optional[Union[authorization_policy.ListAuthorizationPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAuthorizationPoliciesAsyncPager: + r"""Lists AuthorizationPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_list_authorization_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListAuthorizationPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_authorization_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest, dict]]): + The request object. Request used with the + ListAuthorizationPolicies method. + parent (:class:`str`): + Required. The project and location from which the + AuthorizationPolicies should be listed, specified in the + format ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager: + Response returned by the + ListAuthorizationPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.ListAuthorizationPoliciesRequest): + request = authorization_policy.ListAuthorizationPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_authorization_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListAuthorizationPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_authorization_policy(self, + request: Optional[Union[authorization_policy.GetAuthorizationPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> authorization_policy.AuthorizationPolicy: + r"""Gets details of a single AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_get_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_authorization_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.GetAuthorizationPolicyRequest, dict]]): + The request object. Request used by the + GetAuthorizationPolicy method. + name (:class:`str`): + Required. A name of the AuthorizationPolicy to get. Must + be in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.types.AuthorizationPolicy: + AuthorizationPolicy is a resource + that specifies how a server should + authorize incoming connections. This + resource in itself does not change the + configuration unless it's attached to a + target https proxy or endpoint config + selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.GetAuthorizationPolicyRequest): + request = authorization_policy.GetAuthorizationPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_authorization_policy(self, + request: Optional[Union[gcn_authorization_policy.CreateAuthorizationPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, + authorization_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new AuthorizationPolicy in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_create_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1beta1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1beta1.CreateAuthorizationPolicyRequest( + parent="parent_value", + authorization_policy_id="authorization_policy_id_value", + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.create_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.CreateAuthorizationPolicyRequest, dict]]): + The request object. Request used by the + CreateAuthorizationPolicy method. + parent (:class:`str`): + Required. The parent resource of the + AuthorizationPolicy. Must be in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + authorization_policy (:class:`google.cloud.network_security_v1beta1.types.AuthorizationPolicy`): + Required. AuthorizationPolicy + resource to be created. + + This corresponds to the ``authorization_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + authorization_policy_id (:class:`str`): + Required. Short name of the AuthorizationPolicy resource + to be created. This value should be 1-63 characters + long, containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "authz_policy". + + This corresponds to the ``authorization_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1beta1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server + should authorize incoming connections. This resource + in itself does not change the configuration unless + it's attached to a target https proxy or endpoint + config selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, authorization_policy, authorization_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_authorization_policy.CreateAuthorizationPolicyRequest): + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if authorization_policy is not None: + request.authorization_policy = authorization_policy + if authorization_policy_id is not None: + request.authorization_policy_id = authorization_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_authorization_policy.AuthorizationPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_authorization_policy(self, + request: Optional[Union[gcn_authorization_policy.UpdateAuthorizationPolicyRequest, dict]] = None, + *, + authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single + AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_update_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1beta1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1beta1.UpdateAuthorizationPolicyRequest( + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.update_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.UpdateAuthorizationPolicyRequest, dict]]): + The request object. Request used by the + UpdateAuthorizationPolicy method. + authorization_policy (:class:`google.cloud.network_security_v1beta1.types.AuthorizationPolicy`): + Required. Updated AuthorizationPolicy + resource. + + This corresponds to the ``authorization_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the AuthorizationPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1beta1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server + should authorize incoming connections. This resource + in itself does not change the configuration unless + it's attached to a target https proxy or endpoint + config selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [authorization_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_authorization_policy.UpdateAuthorizationPolicyRequest): + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if authorization_policy is not None: + request.authorization_policy = authorization_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_authorization_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("authorization_policy.name", request.authorization_policy.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_authorization_policy.AuthorizationPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_authorization_policy(self, + request: Optional[Union[authorization_policy.DeleteAuthorizationPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_delete_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.DeleteAuthorizationPolicyRequest, dict]]): + The request object. Request used by the + DeleteAuthorizationPolicy method. + name (:class:`str`): + Required. A name of the AuthorizationPolicy to delete. + Must be in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.DeleteAuthorizationPolicyRequest): + request = authorization_policy.DeleteAuthorizationPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_server_tls_policies(self, + request: Optional[Union[server_tls_policy.ListServerTlsPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListServerTlsPoliciesAsyncPager: + r"""Lists ServerTlsPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_list_server_tls_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListServerTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_server_tls_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest, dict]]): + The request object. Request used by the + ListServerTlsPolicies method. + parent (:class:`str`): + Required. The project and location from which the + ServerTlsPolicies should be listed, specified in the + format ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager: + Response returned by the + ListServerTlsPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.ListServerTlsPoliciesRequest): + request = server_tls_policy.ListServerTlsPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_server_tls_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListServerTlsPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_server_tls_policy(self, + request: Optional[Union[server_tls_policy.GetServerTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> server_tls_policy.ServerTlsPolicy: + r"""Gets details of a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_get_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_server_tls_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.GetServerTlsPolicyRequest, dict]]): + The request object. Request used by the + GetServerTlsPolicy method. + name (:class:`str`): + Required. A name of the ServerTlsPolicy to get. Must be + in the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.types.ServerTlsPolicy: + ServerTlsPolicy is a resource that + specifies how a server should + authenticate incoming requests. This + resource itself does not affect + configuration unless it is attached to a + target https proxy or endpoint config + selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.GetServerTlsPolicyRequest): + request = server_tls_policy.GetServerTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_server_tls_policy(self, + request: Optional[Union[gcn_server_tls_policy.CreateServerTlsPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, + server_tls_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ServerTlsPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_create_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1beta1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1beta1.CreateServerTlsPolicyRequest( + parent="parent_value", + server_tls_policy_id="server_tls_policy_id_value", + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.create_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.CreateServerTlsPolicyRequest, dict]]): + The request object. Request used by the + CreateServerTlsPolicy method. + parent (:class:`str`): + Required. The parent resource of the ServerTlsPolicy. + Must be in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + server_tls_policy (:class:`google.cloud.network_security_v1beta1.types.ServerTlsPolicy`): + Required. ServerTlsPolicy resource to + be created. + + This corresponds to the ``server_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + server_tls_policy_id (:class:`str`): + Required. Short name of the ServerTlsPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "server_mtls_policy". + + This corresponds to the ``server_tls_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1beta1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate + incoming requests. This resource itself does not + affect configuration unless it is attached to a + target https proxy or endpoint config selector + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, server_tls_policy, server_tls_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_server_tls_policy.CreateServerTlsPolicyRequest): + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if server_tls_policy is not None: + request.server_tls_policy = server_tls_policy + if server_tls_policy_id is not None: + request.server_tls_policy_id = server_tls_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_server_tls_policy.ServerTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_server_tls_policy(self, + request: Optional[Union[gcn_server_tls_policy.UpdateServerTlsPolicyRequest, dict]] = None, + *, + server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_update_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1beta1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1beta1.UpdateServerTlsPolicyRequest( + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.update_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.UpdateServerTlsPolicyRequest, dict]]): + The request object. Request used by UpdateServerTlsPolicy + method. + server_tls_policy (:class:`google.cloud.network_security_v1beta1.types.ServerTlsPolicy`): + Required. Updated ServerTlsPolicy + resource. + + This corresponds to the ``server_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the ServerTlsPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1beta1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate + incoming requests. This resource itself does not + affect configuration unless it is attached to a + target https proxy or endpoint config selector + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [server_tls_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_server_tls_policy.UpdateServerTlsPolicyRequest): + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if server_tls_policy is not None: + request.server_tls_policy = server_tls_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_server_tls_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("server_tls_policy.name", request.server_tls_policy.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_server_tls_policy.ServerTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_server_tls_policy(self, + request: Optional[Union[server_tls_policy.DeleteServerTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_delete_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.DeleteServerTlsPolicyRequest, dict]]): + The request object. Request used by the + DeleteServerTlsPolicy method. + name (:class:`str`): + Required. A name of the ServerTlsPolicy to delete. Must + be in the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.DeleteServerTlsPolicyRequest): + request = server_tls_policy.DeleteServerTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_client_tls_policies(self, + request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListClientTlsPoliciesAsyncPager: + r"""Lists ClientTlsPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest, dict]]): + The request object. Request used by the + ListClientTlsPolicies method. + parent (:class:`str`): + Required. The project and location from which the + ClientTlsPolicies should be listed, specified in the + format ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager: + Response returned by the + ListClientTlsPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): + request = client_tls_policy.ListClientTlsPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_client_tls_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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.ListClientTlsPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_client_tls_policy(self, + request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> client_tls_policy.ClientTlsPolicy: + r"""Gets details of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.GetClientTlsPolicyRequest, dict]]): + The request object. Request used by the + GetClientTlsPolicy method. + name (:class:`str`): + Required. A name of the ClientTlsPolicy to get. Must be + in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.types.ClientTlsPolicy: + ClientTlsPolicy is a resource that + specifies how a client should + authenticate connections to backends of + a service. This resource itself does not + affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): + request = client_tls_policy.GetClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + client_tls_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ClientTlsPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1beta1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1beta1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.CreateClientTlsPolicyRequest, dict]]): + The request object. Request used by the + CreateClientTlsPolicy method. + parent (:class:`str`): + Required. The parent resource of the ClientTlsPolicy. + Must be in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy (:class:`google.cloud.network_security_v1beta1.types.ClientTlsPolicy`): + Required. ClientTlsPolicy resource to + be created. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy_id (:class:`str`): + Required. Short name of the ClientTlsPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "client_mtls_policy". + + This corresponds to the ``client_tls_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1beta1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, client_tls_policy, client_tls_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if client_tls_policy_id is not None: + request.client_tls_policy_id = client_tls_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, + *, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates the parameters of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1beta1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1beta1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.UpdateClientTlsPolicyRequest, dict]]): + The request object. Request used by UpdateClientTlsPolicy + method. + client_tls_policy (:class:`google.cloud.network_security_v1beta1.types.ClientTlsPolicy`): + Required. Updated ClientTlsPolicy + resource. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the ClientTlsPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + 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.network_security_v1beta1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [client_tls_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_client_tls_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("client_tls_policy.name", request.client_tls_policy.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_client_tls_policy(self, + request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + async def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.network_security_v1beta1.types.DeleteClientTlsPolicyRequest, dict]]): + The request object. Request used by the + DeleteClientTlsPolicy method. + name (:class:`str`): + Required. A name of the ClientTlsPolicy to delete. Must + be in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): + request = client_tls_policy.DeleteClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "NetworkSecurityAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "NetworkSecurityAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/client.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/client.py new file mode 100644 index 000000000000..f5b1f5318f5c --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/client.py @@ -0,0 +1,3251 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.network_security_v1beta1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1beta1.services.network_security import pagers +from google.cloud.network_security_v1beta1.types import authorization_policy +from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1beta1.types import common +from google.cloud.network_security_v1beta1.types import server_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy +from google.cloud.network_security_v1beta1.types import tls +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import NetworkSecurityGrpcTransport +from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport + + +class NetworkSecurityClientMeta(type): + """Metaclass for the NetworkSecurity 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[NetworkSecurityTransport]] + _transport_registry["grpc"] = NetworkSecurityGrpcTransport + _transport_registry["grpc_asyncio"] = NetworkSecurityGrpcAsyncIOTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[NetworkSecurityTransport]: + """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 NetworkSecurityClient(metaclass=NetworkSecurityClientMeta): + """Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + """ + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "networksecurity.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "networksecurity.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @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: + NetworkSecurityClient: 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: + NetworkSecurityClient: 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) -> NetworkSecurityTransport: + """Returns the transport used by the client instance. + + Returns: + NetworkSecurityTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def authorization_policy_path(project: str,location: str,authorization_policy: str,) -> str: + """Returns a fully-qualified authorization_policy string.""" + return "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format(project=project, location=location, authorization_policy=authorization_policy, ) + + @staticmethod + def parse_authorization_policy_path(path: str) -> Dict[str,str]: + """Parses a authorization_policy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/authorizationPolicies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def client_tls_policy_path(project: str,location: str,client_tls_policy: str,) -> str: + """Returns a fully-qualified client_tls_policy string.""" + return "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) + + @staticmethod + def parse_client_tls_policy_path(path: str) -> Dict[str,str]: + """Parses a client_tls_policy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clientTlsPolicies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def server_tls_policy_path(project: str,location: str,server_tls_policy: str,) -> str: + """Returns a fully-qualified server_tls_policy string.""" + return "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format(project=project, location=location, server_tls_policy=server_tls_policy, ) + + @staticmethod + def parse_server_tls_policy_path(path: str) -> Dict[str,str]: + """Parses a server_tls_policy path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/serverTlsPolicies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = NetworkSecurityClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, + error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the network security 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the NetworkSecurityTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "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). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS 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. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = NetworkSecurityClient._read_environment_variables() + self._client_cert_source = NetworkSecurityClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = NetworkSecurityClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, NetworkSecurityTransport) + if transport_provided: + # transport is a NetworkSecurityTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(NetworkSecurityTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + NetworkSecurityClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[NetworkSecurityTransport], Callable[..., NetworkSecurityTransport]] = ( + NetworkSecurityClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., NetworkSecurityTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.networksecurity_v1beta1.NetworkSecurityClient`.", + extra = { + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), + } if hasattr(self._transport, "_credentials") else { + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "credentialsType": None, + } + ) + + def list_authorization_policies(self, + request: Optional[Union[authorization_policy.ListAuthorizationPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAuthorizationPoliciesPager: + r"""Lists AuthorizationPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_list_authorization_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListAuthorizationPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_authorization_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest, dict]): + The request object. Request used with the + ListAuthorizationPolicies method. + parent (str): + Required. The project and location from which the + AuthorizationPolicies should be listed, specified in the + format ``projects/{project}/locations/{location}``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.services.network_security.pagers.ListAuthorizationPoliciesPager: + Response returned by the + ListAuthorizationPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.ListAuthorizationPoliciesRequest): + request = authorization_policy.ListAuthorizationPoliciesRequest(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_authorization_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListAuthorizationPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_authorization_policy(self, + request: Optional[Union[authorization_policy.GetAuthorizationPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> authorization_policy.AuthorizationPolicy: + r"""Gets details of a single AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_get_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_authorization_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.GetAuthorizationPolicyRequest, dict]): + The request object. Request used by the + GetAuthorizationPolicy method. + name (str): + Required. A name of the AuthorizationPolicy to get. Must + be in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.types.AuthorizationPolicy: + AuthorizationPolicy is a resource + that specifies how a server should + authorize incoming connections. This + resource in itself does not change the + configuration unless it's attached to a + target https proxy or endpoint config + selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.GetAuthorizationPolicyRequest): + request = authorization_policy.GetAuthorizationPolicyRequest(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_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_authorization_policy(self, + request: Optional[Union[gcn_authorization_policy.CreateAuthorizationPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, + authorization_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new AuthorizationPolicy in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_create_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1beta1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1beta1.CreateAuthorizationPolicyRequest( + parent="parent_value", + authorization_policy_id="authorization_policy_id_value", + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.create_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.CreateAuthorizationPolicyRequest, dict]): + The request object. Request used by the + CreateAuthorizationPolicy method. + parent (str): + Required. The parent resource of the + AuthorizationPolicy. Must be in the format + ``projects/{project}/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + authorization_policy (google.cloud.network_security_v1beta1.types.AuthorizationPolicy): + Required. AuthorizationPolicy + resource to be created. + + This corresponds to the ``authorization_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + authorization_policy_id (str): + Required. Short name of the AuthorizationPolicy resource + to be created. This value should be 1-63 characters + long, containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "authz_policy". + + This corresponds to the ``authorization_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server + should authorize incoming connections. This resource + in itself does not change the configuration unless + it's attached to a target https proxy or endpoint + config selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, authorization_policy, authorization_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_authorization_policy.CreateAuthorizationPolicyRequest): + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if authorization_policy is not None: + request.authorization_policy = authorization_policy + if authorization_policy_id is not None: + request.authorization_policy_id = authorization_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_authorization_policy.AuthorizationPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_authorization_policy(self, + request: Optional[Union[gcn_authorization_policy.UpdateAuthorizationPolicyRequest, dict]] = None, + *, + authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single + AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_update_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1beta1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1beta1.UpdateAuthorizationPolicyRequest( + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.update_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.UpdateAuthorizationPolicyRequest, dict]): + The request object. Request used by the + UpdateAuthorizationPolicy method. + authorization_policy (google.cloud.network_security_v1beta1.types.AuthorizationPolicy): + Required. Updated AuthorizationPolicy + resource. + + This corresponds to the ``authorization_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the AuthorizationPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server + should authorize incoming connections. This resource + in itself does not change the configuration unless + it's attached to a target https proxy or endpoint + config selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [authorization_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_authorization_policy.UpdateAuthorizationPolicyRequest): + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if authorization_policy is not None: + request.authorization_policy = authorization_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_authorization_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("authorization_policy.name", request.authorization_policy.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_authorization_policy.AuthorizationPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_authorization_policy(self, + request: Optional[Union[authorization_policy.DeleteAuthorizationPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single AuthorizationPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_delete_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.DeleteAuthorizationPolicyRequest, dict]): + The request object. Request used by the + DeleteAuthorizationPolicy method. + name (str): + Required. A name of the AuthorizationPolicy to delete. + Must be in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, authorization_policy.DeleteAuthorizationPolicyRequest): + request = authorization_policy.DeleteAuthorizationPolicyRequest(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_authorization_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_server_tls_policies(self, + request: Optional[Union[server_tls_policy.ListServerTlsPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListServerTlsPoliciesPager: + r"""Lists ServerTlsPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_list_server_tls_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListServerTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_server_tls_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest, dict]): + The request object. Request used by the + ListServerTlsPolicies method. + parent (str): + Required. The project and location from which the + ServerTlsPolicies should be listed, specified in the + format ``projects/*/locations/{location}``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.services.network_security.pagers.ListServerTlsPoliciesPager: + Response returned by the + ListServerTlsPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.ListServerTlsPoliciesRequest): + request = server_tls_policy.ListServerTlsPoliciesRequest(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_server_tls_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListServerTlsPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_server_tls_policy(self, + request: Optional[Union[server_tls_policy.GetServerTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> server_tls_policy.ServerTlsPolicy: + r"""Gets details of a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_get_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_server_tls_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.GetServerTlsPolicyRequest, dict]): + The request object. Request used by the + GetServerTlsPolicy method. + name (str): + Required. A name of the ServerTlsPolicy to get. Must be + in the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.types.ServerTlsPolicy: + ServerTlsPolicy is a resource that + specifies how a server should + authenticate incoming requests. This + resource itself does not affect + configuration unless it is attached to a + target https proxy or endpoint config + selector resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.GetServerTlsPolicyRequest): + request = server_tls_policy.GetServerTlsPolicyRequest(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_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_server_tls_policy(self, + request: Optional[Union[gcn_server_tls_policy.CreateServerTlsPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, + server_tls_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new ServerTlsPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_create_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1beta1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1beta1.CreateServerTlsPolicyRequest( + parent="parent_value", + server_tls_policy_id="server_tls_policy_id_value", + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.create_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.CreateServerTlsPolicyRequest, dict]): + The request object. Request used by the + CreateServerTlsPolicy method. + parent (str): + Required. The parent resource of the ServerTlsPolicy. + Must be in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + server_tls_policy (google.cloud.network_security_v1beta1.types.ServerTlsPolicy): + Required. ServerTlsPolicy resource to + be created. + + This corresponds to the ``server_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + server_tls_policy_id (str): + Required. Short name of the ServerTlsPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "server_mtls_policy". + + This corresponds to the ``server_tls_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate + incoming requests. This resource itself does not + affect configuration unless it is attached to a + target https proxy or endpoint config selector + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, server_tls_policy, server_tls_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_server_tls_policy.CreateServerTlsPolicyRequest): + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if server_tls_policy is not None: + request.server_tls_policy = server_tls_policy + if server_tls_policy_id is not None: + request.server_tls_policy_id = server_tls_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_server_tls_policy.ServerTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_server_tls_policy(self, + request: Optional[Union[gcn_server_tls_policy.UpdateServerTlsPolicyRequest, dict]] = None, + *, + server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_update_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1beta1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1beta1.UpdateServerTlsPolicyRequest( + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.update_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.UpdateServerTlsPolicyRequest, dict]): + The request object. Request used by UpdateServerTlsPolicy + method. + server_tls_policy (google.cloud.network_security_v1beta1.types.ServerTlsPolicy): + Required. Updated ServerTlsPolicy + resource. + + This corresponds to the ``server_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ServerTlsPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate + incoming requests. This resource itself does not + affect configuration unless it is attached to a + target https proxy or endpoint config selector + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [server_tls_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_server_tls_policy.UpdateServerTlsPolicyRequest): + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if server_tls_policy is not None: + request.server_tls_policy = server_tls_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_server_tls_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("server_tls_policy.name", request.server_tls_policy.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_server_tls_policy.ServerTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_server_tls_policy(self, + request: Optional[Union[server_tls_policy.DeleteServerTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single ServerTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_delete_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.DeleteServerTlsPolicyRequest, dict]): + The request object. Request used by the + DeleteServerTlsPolicy method. + name (str): + Required. A name of the ServerTlsPolicy to delete. Must + be in the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, server_tls_policy.DeleteServerTlsPolicyRequest): + request = server_tls_policy.DeleteServerTlsPolicyRequest(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_server_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_client_tls_policies(self, + request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListClientTlsPoliciesPager: + r"""Lists ClientTlsPolicies in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest, dict]): + The request object. Request used by the + ListClientTlsPolicies method. + parent (str): + Required. The project and location from which the + ClientTlsPolicies should be listed, specified in the + format ``projects/*/locations/{location}``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.services.network_security.pagers.ListClientTlsPoliciesPager: + Response returned by the + ListClientTlsPolicies method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): + request = client_tls_policy.ListClientTlsPoliciesRequest(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_client_tls_policies] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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.ListClientTlsPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_client_tls_policy(self, + request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> client_tls_policy.ClientTlsPolicy: + r"""Gets details of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.GetClientTlsPolicyRequest, dict]): + The request object. Request used by the + GetClientTlsPolicy method. + name (str): + Required. A name of the ClientTlsPolicy to get. Must be + in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.network_security_v1beta1.types.ClientTlsPolicy: + ClientTlsPolicy is a resource that + specifies how a client should + authenticate connections to backends of + a service. This resource itself does not + affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): + request = client_tls_policy.GetClientTlsPolicyRequest(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_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + client_tls_policy_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new ClientTlsPolicy in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1beta1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1beta1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.CreateClientTlsPolicyRequest, dict]): + The request object. Request used by the + CreateClientTlsPolicy method. + parent (str): + Required. The parent resource of the ClientTlsPolicy. + Must be in the format + ``projects/*/locations/{location}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy (google.cloud.network_security_v1beta1.types.ClientTlsPolicy): + Required. ClientTlsPolicy resource to + be created. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + client_tls_policy_id (str): + Required. Short name of the ClientTlsPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and + underscores, and should not start with a number. E.g. + "client_mtls_policy". + + This corresponds to the ``client_tls_policy_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, client_tls_policy, client_tls_policy_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if client_tls_policy_id is not None: + request.client_tls_policy_id = client_tls_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_client_tls_policy(self, + request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, + *, + client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates the parameters of a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1beta1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1beta1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.UpdateClientTlsPolicyRequest, dict]): + The request object. Request used by UpdateClientTlsPolicy + method. + client_tls_policy (google.cloud.network_security_v1beta1.types.ClientTlsPolicy): + Required. Updated ClientTlsPolicy + resource. + + This corresponds to the ``client_tls_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ClientTlsPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate + connections to backends of a service. This resource + itself does not affect configuration unless it is + attached to a backend service resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [client_tls_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if client_tls_policy is not None: + request.client_tls_policy = client_tls_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_client_tls_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("client_tls_policy.name", request.client_tls_policy.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # 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, + gcn_client_tls_policy.ClientTlsPolicy, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_client_tls_policy(self, + request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a single ClientTlsPolicy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import network_security_v1beta1 + + def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.network_security_v1beta1.types.DeleteClientTlsPolicyRequest, dict]): + The request object. Request used by the + DeleteClientTlsPolicy method. + name (str): + Required. A name of the ClientTlsPolicy to delete. Must + be in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): + request = client_tls_policy.DeleteClientTlsPolicyRequest(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_client_tls_policy] + + # 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), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "NetworkSecurityClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "NetworkSecurityClient", +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/pagers.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/pagers.py new file mode 100644 index 000000000000..33ade1db16b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/pagers.py @@ -0,0 +1,446 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.network_security_v1beta1.types import authorization_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy + + +class ListAuthorizationPoliciesPager: + """A pager for iterating through ``list_authorization_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``authorization_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAuthorizationPolicies`` requests and continue to iterate + through the ``authorization_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse` + 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[..., authorization_policy.ListAuthorizationPoliciesResponse], + request: authorization_policy.ListAuthorizationPoliciesRequest, + response: authorization_policy.ListAuthorizationPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = authorization_policy.ListAuthorizationPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[authorization_policy.ListAuthorizationPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[authorization_policy.AuthorizationPolicy]: + for page in self.pages: + yield from page.authorization_policies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAuthorizationPoliciesAsyncPager: + """A pager for iterating through ``list_authorization_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``authorization_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAuthorizationPolicies`` requests and continue to iterate + through the ``authorization_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse` + 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[authorization_policy.ListAuthorizationPoliciesResponse]], + request: authorization_policy.ListAuthorizationPoliciesRequest, + response: authorization_policy.ListAuthorizationPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = authorization_policy.ListAuthorizationPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[authorization_policy.ListAuthorizationPoliciesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[authorization_policy.AuthorizationPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.authorization_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServerTlsPoliciesPager: + """A pager for iterating through ``list_server_tls_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``server_tls_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServerTlsPolicies`` requests and continue to iterate + through the ``server_tls_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse` + 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[..., server_tls_policy.ListServerTlsPoliciesResponse], + request: server_tls_policy.ListServerTlsPoliciesRequest, + response: server_tls_policy.ListServerTlsPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = server_tls_policy.ListServerTlsPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[server_tls_policy.ListServerTlsPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[server_tls_policy.ServerTlsPolicy]: + for page in self.pages: + yield from page.server_tls_policies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListServerTlsPoliciesAsyncPager: + """A pager for iterating through ``list_server_tls_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``server_tls_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServerTlsPolicies`` requests and continue to iterate + through the ``server_tls_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse` + 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[server_tls_policy.ListServerTlsPoliciesResponse]], + request: server_tls_policy.ListServerTlsPoliciesRequest, + response: server_tls_policy.ListServerTlsPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = server_tls_policy.ListServerTlsPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[server_tls_policy.ListServerTlsPoliciesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[server_tls_policy.ServerTlsPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.server_tls_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListClientTlsPoliciesPager: + """A pager for iterating through ``list_client_tls_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``client_tls_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListClientTlsPolicies`` requests and continue to iterate + through the ``client_tls_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse` + 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[..., client_tls_policy.ListClientTlsPoliciesResponse], + request: client_tls_policy.ListClientTlsPoliciesRequest, + response: client_tls_policy.ListClientTlsPoliciesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[client_tls_policy.ListClientTlsPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[client_tls_policy.ClientTlsPolicy]: + for page in self.pages: + yield from page.client_tls_policies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListClientTlsPoliciesAsyncPager: + """A pager for iterating through ``list_client_tls_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``client_tls_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListClientTlsPolicies`` requests and continue to iterate + through the ``client_tls_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse` + 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[client_tls_policy.ListClientTlsPoliciesResponse]], + request: client_tls_policy.ListClientTlsPoliciesRequest, + response: client_tls_policy.ListClientTlsPoliciesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest): + The initial request object. + response (google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[client_tls_policy.ListClientTlsPoliciesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[client_tls_policy.ClientTlsPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.client_tls_policies: + 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/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/README.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/README.rst new file mode 100644 index 000000000000..e226a3cdbadb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`NetworkSecurityTransport` is the ABC for all transports. +- public child `NetworkSecurityGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `NetworkSecurityGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseNetworkSecurityRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `NetworkSecurityRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py new file mode 100644 index 000000000000..280f689c5e71 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 NetworkSecurityTransport +from .grpc import NetworkSecurityGrpcTransport +from .grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[NetworkSecurityTransport]] +_transport_registry['grpc'] = NetworkSecurityGrpcTransport +_transport_registry['grpc_asyncio'] = NetworkSecurityGrpcAsyncIOTransport + +__all__ = ( + 'NetworkSecurityTransport', + 'NetworkSecurityGrpcTransport', + 'NetworkSecurityGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/base.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/base.py new file mode 100644 index 000000000000..26a01a6cfc72 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/base.py @@ -0,0 +1,497 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.network_security_v1beta1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1beta1.types import authorization_policy +from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class NetworkSecurityTransport(abc.ABC): + """Abstract transport class for NetworkSecurity.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'networksecurity.googleapis.com' + + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_authorization_policies: gapic_v1.method.wrap_method( + self.list_authorization_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_authorization_policy: gapic_v1.method.wrap_method( + self.get_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_authorization_policy: gapic_v1.method.wrap_method( + self.create_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_authorization_policy: gapic_v1.method.wrap_method( + self.update_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_authorization_policy: gapic_v1.method.wrap_method( + self.delete_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_server_tls_policies: gapic_v1.method.wrap_method( + self.list_server_tls_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_server_tls_policy: gapic_v1.method.wrap_method( + self.get_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_server_tls_policy: gapic_v1.method.wrap_method( + self.create_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_server_tls_policy: gapic_v1.method.wrap_method( + self.update_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_server_tls_policy: gapic_v1.method.wrap_method( + self.delete_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_client_tls_policies: gapic_v1.method.wrap_method( + self.list_client_tls_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_client_tls_policy: gapic_v1.method.wrap_method( + self.get_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_client_tls_policy: gapic_v1.method.wrap_method( + self.create_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_client_tls_policy: gapic_v1.method.wrap_method( + self.update_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_client_tls_policy: gapic_v1.method.wrap_method( + self.delete_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_authorization_policies(self) -> Callable[ + [authorization_policy.ListAuthorizationPoliciesRequest], + Union[ + authorization_policy.ListAuthorizationPoliciesResponse, + Awaitable[authorization_policy.ListAuthorizationPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def get_authorization_policy(self) -> Callable[ + [authorization_policy.GetAuthorizationPolicyRequest], + Union[ + authorization_policy.AuthorizationPolicy, + Awaitable[authorization_policy.AuthorizationPolicy] + ]]: + raise NotImplementedError() + + @property + def create_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.CreateAuthorizationPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_authorization_policy(self) -> Callable[ + [authorization_policy.DeleteAuthorizationPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_server_tls_policies(self) -> Callable[ + [server_tls_policy.ListServerTlsPoliciesRequest], + Union[ + server_tls_policy.ListServerTlsPoliciesResponse, + Awaitable[server_tls_policy.ListServerTlsPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def get_server_tls_policy(self) -> Callable[ + [server_tls_policy.GetServerTlsPolicyRequest], + Union[ + server_tls_policy.ServerTlsPolicy, + Awaitable[server_tls_policy.ServerTlsPolicy] + ]]: + raise NotImplementedError() + + @property + def create_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.CreateServerTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_server_tls_policy(self) -> Callable[ + [server_tls_policy.DeleteServerTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + Union[ + client_tls_policy.ListClientTlsPoliciesResponse, + Awaitable[client_tls_policy.ListClientTlsPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + Union[ + client_tls_policy.ClientTlsPolicy, + Awaitable[client_tls_policy.ClientTlsPolicy] + ]]: + raise NotImplementedError() + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'NetworkSecurityTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc.py new file mode 100644 index 000000000000..38be51141758 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc.py @@ -0,0 +1,933 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1beta1.types import authorization_policy +from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class NetworkSecurityGrpcTransport(NetworkSecurityTransport): + """gRPC backend transport for NetworkSecurity. + + Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_authorization_policies(self) -> Callable[ + [authorization_policy.ListAuthorizationPoliciesRequest], + authorization_policy.ListAuthorizationPoliciesResponse]: + r"""Return a callable for the list authorization policies method over gRPC. + + Lists AuthorizationPolicies in a given project and + location. + + Returns: + Callable[[~.ListAuthorizationPoliciesRequest], + ~.ListAuthorizationPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_authorization_policies' not in self._stubs: + self._stubs['list_authorization_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListAuthorizationPolicies', + request_serializer=authorization_policy.ListAuthorizationPoliciesRequest.serialize, + response_deserializer=authorization_policy.ListAuthorizationPoliciesResponse.deserialize, + ) + return self._stubs['list_authorization_policies'] + + @property + def get_authorization_policy(self) -> Callable[ + [authorization_policy.GetAuthorizationPolicyRequest], + authorization_policy.AuthorizationPolicy]: + r"""Return a callable for the get authorization policy method over gRPC. + + Gets details of a single AuthorizationPolicy. + + Returns: + Callable[[~.GetAuthorizationPolicyRequest], + ~.AuthorizationPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_authorization_policy' not in self._stubs: + self._stubs['get_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetAuthorizationPolicy', + request_serializer=authorization_policy.GetAuthorizationPolicyRequest.serialize, + response_deserializer=authorization_policy.AuthorizationPolicy.deserialize, + ) + return self._stubs['get_authorization_policy'] + + @property + def create_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.CreateAuthorizationPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the create authorization policy method over gRPC. + + Creates a new AuthorizationPolicy in a given project + and location. + + Returns: + Callable[[~.CreateAuthorizationPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_authorization_policy' not in self._stubs: + self._stubs['create_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateAuthorizationPolicy', + request_serializer=gcn_authorization_policy.CreateAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_authorization_policy'] + + @property + def update_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the update authorization policy method over gRPC. + + Updates the parameters of a single + AuthorizationPolicy. + + Returns: + Callable[[~.UpdateAuthorizationPolicyRequest], + ~.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 'update_authorization_policy' not in self._stubs: + self._stubs['update_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateAuthorizationPolicy', + request_serializer=gcn_authorization_policy.UpdateAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_authorization_policy'] + + @property + def delete_authorization_policy(self) -> Callable[ + [authorization_policy.DeleteAuthorizationPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete authorization policy method over gRPC. + + Deletes a single AuthorizationPolicy. + + Returns: + Callable[[~.DeleteAuthorizationPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_authorization_policy' not in self._stubs: + self._stubs['delete_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteAuthorizationPolicy', + request_serializer=authorization_policy.DeleteAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_authorization_policy'] + + @property + def list_server_tls_policies(self) -> Callable[ + [server_tls_policy.ListServerTlsPoliciesRequest], + server_tls_policy.ListServerTlsPoliciesResponse]: + r"""Return a callable for the list server tls policies method over gRPC. + + Lists ServerTlsPolicies in a given project and + location. + + Returns: + Callable[[~.ListServerTlsPoliciesRequest], + ~.ListServerTlsPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_server_tls_policies' not in self._stubs: + self._stubs['list_server_tls_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListServerTlsPolicies', + request_serializer=server_tls_policy.ListServerTlsPoliciesRequest.serialize, + response_deserializer=server_tls_policy.ListServerTlsPoliciesResponse.deserialize, + ) + return self._stubs['list_server_tls_policies'] + + @property + def get_server_tls_policy(self) -> Callable[ + [server_tls_policy.GetServerTlsPolicyRequest], + server_tls_policy.ServerTlsPolicy]: + r"""Return a callable for the get server tls policy method over gRPC. + + Gets details of a single ServerTlsPolicy. + + Returns: + Callable[[~.GetServerTlsPolicyRequest], + ~.ServerTlsPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_server_tls_policy' not in self._stubs: + self._stubs['get_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetServerTlsPolicy', + request_serializer=server_tls_policy.GetServerTlsPolicyRequest.serialize, + response_deserializer=server_tls_policy.ServerTlsPolicy.deserialize, + ) + return self._stubs['get_server_tls_policy'] + + @property + def create_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.CreateServerTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the create server tls policy method over gRPC. + + Creates a new ServerTlsPolicy in a given project and + location. + + Returns: + Callable[[~.CreateServerTlsPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_server_tls_policy' not in self._stubs: + self._stubs['create_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateServerTlsPolicy', + request_serializer=gcn_server_tls_policy.CreateServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_server_tls_policy'] + + @property + def update_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the update server tls policy method over gRPC. + + Updates the parameters of a single ServerTlsPolicy. + + Returns: + Callable[[~.UpdateServerTlsPolicyRequest], + ~.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 'update_server_tls_policy' not in self._stubs: + self._stubs['update_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateServerTlsPolicy', + request_serializer=gcn_server_tls_policy.UpdateServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_server_tls_policy'] + + @property + def delete_server_tls_policy(self) -> Callable[ + [server_tls_policy.DeleteServerTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete server tls policy method over gRPC. + + Deletes a single ServerTlsPolicy. + + Returns: + Callable[[~.DeleteServerTlsPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_server_tls_policy' not in self._stubs: + self._stubs['delete_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteServerTlsPolicy', + request_serializer=server_tls_policy.DeleteServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_server_tls_policy'] + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + client_tls_policy.ListClientTlsPoliciesResponse]: + r"""Return a callable for the list client tls policies method over gRPC. + + Lists ClientTlsPolicies in a given project and + location. + + Returns: + Callable[[~.ListClientTlsPoliciesRequest], + ~.ListClientTlsPoliciesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: + self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListClientTlsPolicies', + request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, + response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, + ) + return self._stubs['list_client_tls_policies'] + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + client_tls_policy.ClientTlsPolicy]: + r"""Return a callable for the get client tls policy method over gRPC. + + Gets details of a single ClientTlsPolicy. + + Returns: + Callable[[~.GetClientTlsPolicyRequest], + ~.ClientTlsPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: + self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetClientTlsPolicy', + request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, + response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, + ) + return self._stubs['get_client_tls_policy'] + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the create client tls policy method over gRPC. + + Creates a new ClientTlsPolicy in a given project and + location. + + Returns: + Callable[[~.CreateClientTlsPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_client_tls_policy' not in self._stubs: + self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_client_tls_policy'] + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the update client tls policy method over gRPC. + + Updates the parameters of a single ClientTlsPolicy. + + Returns: + Callable[[~.UpdateClientTlsPolicyRequest], + ~.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 'update_client_tls_policy' not in self._stubs: + self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_client_tls_policy'] + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete client tls policy method over gRPC. + + Deletes a single ClientTlsPolicy. + + Returns: + Callable[[~.DeleteClientTlsPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_client_tls_policy' not in self._stubs: + self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteClientTlsPolicy', + request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_client_tls_policy'] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'NetworkSecurityGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc_asyncio.py new file mode 100644 index 000000000000..8b645d639442 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc_asyncio.py @@ -0,0 +1,1069 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.cloud.network_security_v1beta1.types import authorization_policy +from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO +from .grpc import NetworkSecurityGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra = { + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class NetworkSecurityGrpcAsyncIOTransport(NetworkSecurityTransport): + """gRPC AsyncIO backend transport for NetworkSecurity. + + Network Security API provides resources to configure + authentication and authorization policies. Refer to per API + resource documentation for more information. + + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + 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 = 'networksecurity.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'networksecurity.googleapis.com'). + 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_authorization_policies(self) -> Callable[ + [authorization_policy.ListAuthorizationPoliciesRequest], + Awaitable[authorization_policy.ListAuthorizationPoliciesResponse]]: + r"""Return a callable for the list authorization policies method over gRPC. + + Lists AuthorizationPolicies in a given project and + location. + + Returns: + Callable[[~.ListAuthorizationPoliciesRequest], + Awaitable[~.ListAuthorizationPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_authorization_policies' not in self._stubs: + self._stubs['list_authorization_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListAuthorizationPolicies', + request_serializer=authorization_policy.ListAuthorizationPoliciesRequest.serialize, + response_deserializer=authorization_policy.ListAuthorizationPoliciesResponse.deserialize, + ) + return self._stubs['list_authorization_policies'] + + @property + def get_authorization_policy(self) -> Callable[ + [authorization_policy.GetAuthorizationPolicyRequest], + Awaitable[authorization_policy.AuthorizationPolicy]]: + r"""Return a callable for the get authorization policy method over gRPC. + + Gets details of a single AuthorizationPolicy. + + Returns: + Callable[[~.GetAuthorizationPolicyRequest], + Awaitable[~.AuthorizationPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_authorization_policy' not in self._stubs: + self._stubs['get_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetAuthorizationPolicy', + request_serializer=authorization_policy.GetAuthorizationPolicyRequest.serialize, + response_deserializer=authorization_policy.AuthorizationPolicy.deserialize, + ) + return self._stubs['get_authorization_policy'] + + @property + def create_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.CreateAuthorizationPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create authorization policy method over gRPC. + + Creates a new AuthorizationPolicy in a given project + and location. + + Returns: + Callable[[~.CreateAuthorizationPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_authorization_policy' not in self._stubs: + self._stubs['create_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateAuthorizationPolicy', + request_serializer=gcn_authorization_policy.CreateAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_authorization_policy'] + + @property + def update_authorization_policy(self) -> Callable[ + [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update authorization policy method over gRPC. + + Updates the parameters of a single + AuthorizationPolicy. + + Returns: + Callable[[~.UpdateAuthorizationPolicyRequest], + 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 'update_authorization_policy' not in self._stubs: + self._stubs['update_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateAuthorizationPolicy', + request_serializer=gcn_authorization_policy.UpdateAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_authorization_policy'] + + @property + def delete_authorization_policy(self) -> Callable[ + [authorization_policy.DeleteAuthorizationPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete authorization policy method over gRPC. + + Deletes a single AuthorizationPolicy. + + Returns: + Callable[[~.DeleteAuthorizationPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_authorization_policy' not in self._stubs: + self._stubs['delete_authorization_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteAuthorizationPolicy', + request_serializer=authorization_policy.DeleteAuthorizationPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_authorization_policy'] + + @property + def list_server_tls_policies(self) -> Callable[ + [server_tls_policy.ListServerTlsPoliciesRequest], + Awaitable[server_tls_policy.ListServerTlsPoliciesResponse]]: + r"""Return a callable for the list server tls policies method over gRPC. + + Lists ServerTlsPolicies in a given project and + location. + + Returns: + Callable[[~.ListServerTlsPoliciesRequest], + Awaitable[~.ListServerTlsPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_server_tls_policies' not in self._stubs: + self._stubs['list_server_tls_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListServerTlsPolicies', + request_serializer=server_tls_policy.ListServerTlsPoliciesRequest.serialize, + response_deserializer=server_tls_policy.ListServerTlsPoliciesResponse.deserialize, + ) + return self._stubs['list_server_tls_policies'] + + @property + def get_server_tls_policy(self) -> Callable[ + [server_tls_policy.GetServerTlsPolicyRequest], + Awaitable[server_tls_policy.ServerTlsPolicy]]: + r"""Return a callable for the get server tls policy method over gRPC. + + Gets details of a single ServerTlsPolicy. + + Returns: + Callable[[~.GetServerTlsPolicyRequest], + Awaitable[~.ServerTlsPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_server_tls_policy' not in self._stubs: + self._stubs['get_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetServerTlsPolicy', + request_serializer=server_tls_policy.GetServerTlsPolicyRequest.serialize, + response_deserializer=server_tls_policy.ServerTlsPolicy.deserialize, + ) + return self._stubs['get_server_tls_policy'] + + @property + def create_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.CreateServerTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create server tls policy method over gRPC. + + Creates a new ServerTlsPolicy in a given project and + location. + + Returns: + Callable[[~.CreateServerTlsPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_server_tls_policy' not in self._stubs: + self._stubs['create_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateServerTlsPolicy', + request_serializer=gcn_server_tls_policy.CreateServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_server_tls_policy'] + + @property + def update_server_tls_policy(self) -> Callable[ + [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update server tls policy method over gRPC. + + Updates the parameters of a single ServerTlsPolicy. + + Returns: + Callable[[~.UpdateServerTlsPolicyRequest], + 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 'update_server_tls_policy' not in self._stubs: + self._stubs['update_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateServerTlsPolicy', + request_serializer=gcn_server_tls_policy.UpdateServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_server_tls_policy'] + + @property + def delete_server_tls_policy(self) -> Callable[ + [server_tls_policy.DeleteServerTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete server tls policy method over gRPC. + + Deletes a single ServerTlsPolicy. + + Returns: + Callable[[~.DeleteServerTlsPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_server_tls_policy' not in self._stubs: + self._stubs['delete_server_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteServerTlsPolicy', + request_serializer=server_tls_policy.DeleteServerTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_server_tls_policy'] + + @property + def list_client_tls_policies(self) -> Callable[ + [client_tls_policy.ListClientTlsPoliciesRequest], + Awaitable[client_tls_policy.ListClientTlsPoliciesResponse]]: + r"""Return a callable for the list client tls policies method over gRPC. + + Lists ClientTlsPolicies in a given project and + location. + + Returns: + Callable[[~.ListClientTlsPoliciesRequest], + Awaitable[~.ListClientTlsPoliciesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: + self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListClientTlsPolicies', + request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, + response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, + ) + return self._stubs['list_client_tls_policies'] + + @property + def get_client_tls_policy(self) -> Callable[ + [client_tls_policy.GetClientTlsPolicyRequest], + Awaitable[client_tls_policy.ClientTlsPolicy]]: + r"""Return a callable for the get client tls policy method over gRPC. + + Gets details of a single ClientTlsPolicy. + + Returns: + Callable[[~.GetClientTlsPolicyRequest], + Awaitable[~.ClientTlsPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: + self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetClientTlsPolicy', + request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, + response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, + ) + return self._stubs['get_client_tls_policy'] + + @property + def create_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.CreateClientTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create client tls policy method over gRPC. + + Creates a new ClientTlsPolicy in a given project and + location. + + Returns: + Callable[[~.CreateClientTlsPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_client_tls_policy' not in self._stubs: + self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_client_tls_policy'] + + @property + def update_client_tls_policy(self) -> Callable[ + [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update client tls policy method over gRPC. + + Updates the parameters of a single ClientTlsPolicy. + + Returns: + Callable[[~.UpdateClientTlsPolicyRequest], + 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 'update_client_tls_policy' not in self._stubs: + self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateClientTlsPolicy', + request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_client_tls_policy'] + + @property + def delete_client_tls_policy(self) -> Callable[ + [client_tls_policy.DeleteClientTlsPolicyRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete client tls policy method over gRPC. + + Deletes a single ClientTlsPolicy. + + Returns: + Callable[[~.DeleteClientTlsPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_client_tls_policy' not in self._stubs: + self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( + '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteClientTlsPolicy', + request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_client_tls_policy'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_authorization_policies: self._wrap_method( + self.list_authorization_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_authorization_policy: self._wrap_method( + self.get_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_authorization_policy: self._wrap_method( + self.create_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_authorization_policy: self._wrap_method( + self.update_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_authorization_policy: self._wrap_method( + self.delete_authorization_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_server_tls_policies: self._wrap_method( + self.list_server_tls_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_server_tls_policy: self._wrap_method( + self.get_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_server_tls_policy: self._wrap_method( + self.create_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_server_tls_policy: self._wrap_method( + self.update_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_server_tls_policy: self._wrap_method( + self.delete_server_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_client_tls_policies: self._wrap_method( + self.list_client_tls_policies, + default_timeout=None, + client_info=client_info, + ), + self.get_client_tls_policy: self._wrap_method( + self.get_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.create_client_tls_policy: self._wrap_method( + self.create_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_client_tls_policy: self._wrap_method( + self.update_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_client_tls_policy: self._wrap_method( + self.delete_client_tls_policy, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'NetworkSecurityGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/__init__.py new file mode 100644 index 000000000000..bda341b438ae --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .authorization_policy import ( + AuthorizationPolicy, + CreateAuthorizationPolicyRequest, + DeleteAuthorizationPolicyRequest, + GetAuthorizationPolicyRequest, + ListAuthorizationPoliciesRequest, + ListAuthorizationPoliciesResponse, + UpdateAuthorizationPolicyRequest, +) +from .client_tls_policy import ( + ClientTlsPolicy, + CreateClientTlsPolicyRequest, + DeleteClientTlsPolicyRequest, + GetClientTlsPolicyRequest, + ListClientTlsPoliciesRequest, + ListClientTlsPoliciesResponse, + UpdateClientTlsPolicyRequest, +) +from .common import ( + OperationMetadata, +) +from .server_tls_policy import ( + CreateServerTlsPolicyRequest, + DeleteServerTlsPolicyRequest, + GetServerTlsPolicyRequest, + ListServerTlsPoliciesRequest, + ListServerTlsPoliciesResponse, + ServerTlsPolicy, + UpdateServerTlsPolicyRequest, +) +from .tls import ( + CertificateProvider, + CertificateProviderInstance, + GrpcEndpoint, + ValidationCA, +) + +__all__ = ( + 'AuthorizationPolicy', + 'CreateAuthorizationPolicyRequest', + 'DeleteAuthorizationPolicyRequest', + 'GetAuthorizationPolicyRequest', + 'ListAuthorizationPoliciesRequest', + 'ListAuthorizationPoliciesResponse', + 'UpdateAuthorizationPolicyRequest', + 'ClientTlsPolicy', + 'CreateClientTlsPolicyRequest', + 'DeleteClientTlsPolicyRequest', + 'GetClientTlsPolicyRequest', + 'ListClientTlsPoliciesRequest', + 'ListClientTlsPoliciesResponse', + 'UpdateClientTlsPolicyRequest', + 'OperationMetadata', + 'CreateServerTlsPolicyRequest', + 'DeleteServerTlsPolicyRequest', + 'GetServerTlsPolicyRequest', + 'ListServerTlsPoliciesRequest', + 'ListServerTlsPoliciesResponse', + 'ServerTlsPolicy', + 'UpdateServerTlsPolicyRequest', + 'CertificateProvider', + 'CertificateProviderInstance', + 'GrpcEndpoint', + 'ValidationCA', +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/authorization_policy.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/authorization_policy.py new file mode 100644 index 000000000000..f9548bef9e17 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/authorization_policy.py @@ -0,0 +1,425 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1beta1', + manifest={ + 'AuthorizationPolicy', + 'ListAuthorizationPoliciesRequest', + 'ListAuthorizationPoliciesResponse', + 'GetAuthorizationPolicyRequest', + 'CreateAuthorizationPolicyRequest', + 'UpdateAuthorizationPolicyRequest', + 'DeleteAuthorizationPolicyRequest', + }, +) + + +class AuthorizationPolicy(proto.Message): + r"""AuthorizationPolicy is a resource that specifies how a server + should authorize incoming connections. This resource in itself + does not change the configuration unless it's attached to a + target https proxy or endpoint config selector resource. + + Attributes: + name (str): + Required. Name of the AuthorizationPolicy resource. It + matches pattern + ``projects/{project}/locations/{location}/authorizationPolicies/``. + description (str): + Optional. Free-text description of the + resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + labels (MutableMapping[str, str]): + Optional. Set of label tags associated with + the AuthorizationPolicy resource. + action (google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Action): + Required. The action to take when a rule + match is found. Possible values are "ALLOW" or + "DENY". + rules (MutableSequence[google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Rule]): + Optional. List of rules to match. Note that at least one of + the rules must match in order for the action specified in + the 'action' field to be taken. A rule is a match if there + is a matching source and destination. If left blank, the + action specified in the ``action`` field will be applied on + every request. + """ + class Action(proto.Enum): + r"""Possible values that define what action to take. + + Values: + ACTION_UNSPECIFIED (0): + Default value. + ALLOW (1): + Grant access. + DENY (2): + Deny access. + Deny rules should be avoided unless they are + used to provide a default "deny all" fallback. + """ + ACTION_UNSPECIFIED = 0 + ALLOW = 1 + DENY = 2 + + class Rule(proto.Message): + r"""Specification of rules. + + Attributes: + sources (MutableSequence[google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Rule.Source]): + Optional. List of attributes for the traffic source. All of + the sources must match. A source is a match if both + principals and ip_blocks match. If not set, the action + specified in the 'action' field will be applied without any + rule checks for the source. + destinations (MutableSequence[google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Rule.Destination]): + Optional. List of attributes for the traffic + destination. All of the destinations must match. + A destination is a match if a request matches + all the specified hosts, ports, methods and + headers. If not set, the action specified in the + 'action' field will be applied without any rule + checks for the destination. + """ + + class Source(proto.Message): + r"""Specification of traffic source attributes. + + Attributes: + principals (MutableSequence[str]): + Optional. List of peer identities to match for + authorization. At least one principal should match. Each + peer can be an exact match, or a prefix match (example, + "namespace/*") or a suffix match (example, + "*/service-account") or a presence match "*". Authorization + based on the principal name without certificate validation + (configured by ServerTlsPolicy resource) is considered + insecure. + ip_blocks (MutableSequence[str]): + Optional. List of CIDR ranges to match based + on source IP address. At least one IP block + should match. Single IP (e.g., "1.2.3.4") and + CIDR (e.g., "1.2.3.0/24") are supported. + Authorization based on source IP alone should be + avoided. The IP addresses of any load balancers + or proxies should be considered untrusted. + """ + + principals: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + ip_blocks: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class Destination(proto.Message): + r"""Specification of traffic destination attributes. + + Attributes: + hosts (MutableSequence[str]): + Required. List of host names to match. Matched against the + ":authority" header in http requests. At least one host + should match. Each host can be an exact match, or a prefix + match (example "mydomain.*") or a suffix match (example + "*.myorg.com") or a presence (any) match "*". + ports (MutableSequence[int]): + Required. List of destination ports to match. + At least one port should match. + methods (MutableSequence[str]): + Optional. A list of HTTP methods to match. At + least one method should match. Should not be set + for gRPC services. + http_header_match (google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Rule.Destination.HttpHeaderMatch): + Optional. Match against key:value pair in + http header. Provides a flexible match based on + HTTP headers, for potentially advanced use + cases. At least one header should match. Avoid + using header matches to make authorization + decisions unless there is a strong guarantee + that requests arrive through a trusted client or + proxy. + """ + + class HttpHeaderMatch(proto.Message): + r"""Specification of HTTP header match attributes. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + regex_match (str): + Required. The value of the header must match + the regular expression specified in regexMatch. + For regular expression grammar, please see: + en.cppreference.com/w/cpp/regex/ecmascript For + matching against a port specified in the HTTP + request, use a headerMatch with headerName set + to Host and a regular expression that satisfies + the RFC2616 Host header's port specifier. + + This field is a member of `oneof`_ ``type``. + header_name (str): + Required. The name of the HTTP header to + match. For matching against the HTTP request's + authority, use a headerMatch with the header + name ":authority". For matching a request's + method, use the headerName ":method". + """ + + regex_match: str = proto.Field( + proto.STRING, + number=2, + oneof='type', + ) + header_name: str = proto.Field( + proto.STRING, + number=1, + ) + + hosts: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + ports: MutableSequence[int] = proto.RepeatedField( + proto.UINT32, + number=2, + ) + methods: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + http_header_match: 'AuthorizationPolicy.Rule.Destination.HttpHeaderMatch' = proto.Field( + proto.MESSAGE, + number=5, + message='AuthorizationPolicy.Rule.Destination.HttpHeaderMatch', + ) + + sources: MutableSequence['AuthorizationPolicy.Rule.Source'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AuthorizationPolicy.Rule.Source', + ) + destinations: MutableSequence['AuthorizationPolicy.Rule.Destination'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AuthorizationPolicy.Rule.Destination', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + action: Action = proto.Field( + proto.ENUM, + number=6, + enum=Action, + ) + rules: MutableSequence[Rule] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Rule, + ) + + +class ListAuthorizationPoliciesRequest(proto.Message): + r"""Request used with the ListAuthorizationPolicies method. + + Attributes: + parent (str): + Required. The project and location from which the + AuthorizationPolicies should be listed, specified in the + format ``projects/{project}/locations/{location}``. + page_size (int): + Maximum number of AuthorizationPolicies to + return per call. + page_token (str): + The value returned by the last + ``ListAuthorizationPoliciesResponse`` Indicates that this is + a continuation of a prior ``ListAuthorizationPolicies`` + call, and that the system should return the next page of + data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAuthorizationPoliciesResponse(proto.Message): + r"""Response returned by the ListAuthorizationPolicies method. + + Attributes: + authorization_policies (MutableSequence[google.cloud.network_security_v1beta1.types.AuthorizationPolicy]): + List of AuthorizationPolicies resources. + next_page_token (str): + If there might be 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 + + authorization_policies: MutableSequence['AuthorizationPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AuthorizationPolicy', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAuthorizationPolicyRequest(proto.Message): + r"""Request used by the GetAuthorizationPolicy method. + + Attributes: + name (str): + Required. A name of the AuthorizationPolicy to get. Must be + in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAuthorizationPolicyRequest(proto.Message): + r"""Request used by the CreateAuthorizationPolicy method. + + Attributes: + parent (str): + Required. The parent resource of the AuthorizationPolicy. + Must be in the format + ``projects/{project}/locations/{location}``. + authorization_policy_id (str): + Required. Short name of the AuthorizationPolicy resource to + be created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and underscores, + and should not start with a number. E.g. "authz_policy". + authorization_policy (google.cloud.network_security_v1beta1.types.AuthorizationPolicy): + Required. AuthorizationPolicy resource to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + authorization_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + authorization_policy: 'AuthorizationPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='AuthorizationPolicy', + ) + + +class UpdateAuthorizationPolicyRequest(proto.Message): + r"""Request used by the UpdateAuthorizationPolicy method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the AuthorizationPolicy resource by the + update. The fields specified in the update_mask are relative + to the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + authorization_policy (google.cloud.network_security_v1beta1.types.AuthorizationPolicy): + Required. Updated AuthorizationPolicy + resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + authorization_policy: 'AuthorizationPolicy' = proto.Field( + proto.MESSAGE, + number=2, + message='AuthorizationPolicy', + ) + + +class DeleteAuthorizationPolicyRequest(proto.Message): + r"""Request used by the DeleteAuthorizationPolicy method. + + Attributes: + name (str): + Required. A name of the AuthorizationPolicy to delete. Must + be in the format + ``projects/{project}/locations/{location}/authorizationPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/client_tls_policy.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/client_tls_policy.py new file mode 100644 index 000000000000..f3b6cf5050bb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/client_tls_policy.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.network_security_v1beta1.types import tls +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1beta1', + manifest={ + 'ClientTlsPolicy', + 'ListClientTlsPoliciesRequest', + 'ListClientTlsPoliciesResponse', + 'GetClientTlsPolicyRequest', + 'CreateClientTlsPolicyRequest', + 'UpdateClientTlsPolicyRequest', + 'DeleteClientTlsPolicyRequest', + }, +) + + +class ClientTlsPolicy(proto.Message): + r"""ClientTlsPolicy is a resource that specifies how a client + should authenticate connections to backends of a service. This + resource itself does not affect configuration unless it is + attached to a backend service resource. + + Attributes: + name (str): + Required. Name of the ClientTlsPolicy resource. It matches + the pattern + ``projects/*/locations/{location}/clientTlsPolicies/{client_tls_policy}`` + description (str): + Optional. Free-text description of the + resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + labels (MutableMapping[str, str]): + Optional. Set of label tags associated with + the resource. + sni (str): + Optional. Server Name Indication string to + present to the server during TLS handshake. E.g: + "secure.example.com". + client_certificate (google.cloud.network_security_v1beta1.types.CertificateProvider): + Optional. Defines a mechanism to provision + client identity (public and private keys) for + peer to peer authentication. The presence of + this dictates mTLS. + server_validation_ca (MutableSequence[google.cloud.network_security_v1beta1.types.ValidationCA]): + Optional. Defines the mechanism to obtain the + Certificate Authority certificate to validate + the server certificate. If empty, client does + not validate the server certificate. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + sni: str = proto.Field( + proto.STRING, + number=6, + ) + client_certificate: tls.CertificateProvider = proto.Field( + proto.MESSAGE, + number=7, + message=tls.CertificateProvider, + ) + server_validation_ca: MutableSequence[tls.ValidationCA] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=tls.ValidationCA, + ) + + +class ListClientTlsPoliciesRequest(proto.Message): + r"""Request used by the ListClientTlsPolicies method. + + Attributes: + parent (str): + Required. The project and location from which the + ClientTlsPolicies should be listed, specified in the format + ``projects/*/locations/{location}``. + page_size (int): + Maximum number of ClientTlsPolicies to return + per call. + page_token (str): + The value returned by the last + ``ListClientTlsPoliciesResponse`` Indicates that this is a + continuation of a prior ``ListClientTlsPolicies`` call, and + that the system should return the next page of data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListClientTlsPoliciesResponse(proto.Message): + r"""Response returned by the ListClientTlsPolicies method. + + Attributes: + client_tls_policies (MutableSequence[google.cloud.network_security_v1beta1.types.ClientTlsPolicy]): + List of ClientTlsPolicy resources. + next_page_token (str): + If there might be 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 + + client_tls_policies: MutableSequence['ClientTlsPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ClientTlsPolicy', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetClientTlsPolicyRequest(proto.Message): + r"""Request used by the GetClientTlsPolicy method. + + Attributes: + name (str): + Required. A name of the ClientTlsPolicy to get. Must be in + the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateClientTlsPolicyRequest(proto.Message): + r"""Request used by the CreateClientTlsPolicy method. + + Attributes: + parent (str): + Required. The parent resource of the ClientTlsPolicy. Must + be in the format ``projects/*/locations/{location}``. + client_tls_policy_id (str): + Required. Short name of the ClientTlsPolicy resource to be + created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and underscores, + and should not start with a number. E.g. + "client_mtls_policy". + client_tls_policy (google.cloud.network_security_v1beta1.types.ClientTlsPolicy): + Required. ClientTlsPolicy resource to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + client_tls_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + client_tls_policy: 'ClientTlsPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='ClientTlsPolicy', + ) + + +class UpdateClientTlsPolicyRequest(proto.Message): + r"""Request used by UpdateClientTlsPolicy method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ClientTlsPolicy resource by the update. + The fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + client_tls_policy (google.cloud.network_security_v1beta1.types.ClientTlsPolicy): + Required. Updated ClientTlsPolicy resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + client_tls_policy: 'ClientTlsPolicy' = proto.Field( + proto.MESSAGE, + number=2, + message='ClientTlsPolicy', + ) + + +class DeleteClientTlsPolicyRequest(proto.Message): + r"""Request used by the DeleteClientTlsPolicy method. + + Attributes: + name (str): + Required. A name of the ClientTlsPolicy to delete. Must be + in the format + ``projects/*/locations/{location}/clientTlsPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/common.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/common.py new file mode 100644 index 000000000000..2a5468412eb1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/common.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1beta1', + manifest={ + 'OperationMetadata', + }, +) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + target (str): + Output only. Server-defined resource path for + the target of the operation. + verb (str): + Output only. Name of the verb executed by the + operation. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have + successfully been cancelled have [Operation.error][] value + with a [google.rpc.Status.code][google.rpc.Status.code] of + 1, corresponding to ``Code.CANCELLED``. + api_version (str): + Output only. API version used to start the + operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/network_security.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/network_security.py new file mode 100644 index 000000000000..39f8dac22cf5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/network_security.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1beta1', + manifest={ + }, +) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/server_tls_policy.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/server_tls_policy.py new file mode 100644 index 000000000000..398e8f39b3d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/server_tls_policy.py @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.network_security_v1beta1.types import tls +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1beta1', + manifest={ + 'ServerTlsPolicy', + 'ListServerTlsPoliciesRequest', + 'ListServerTlsPoliciesResponse', + 'GetServerTlsPolicyRequest', + 'CreateServerTlsPolicyRequest', + 'UpdateServerTlsPolicyRequest', + 'DeleteServerTlsPolicyRequest', + }, +) + + +class ServerTlsPolicy(proto.Message): + r"""ServerTlsPolicy is a resource that specifies how a server + should authenticate incoming requests. This resource itself does + not affect configuration unless it is attached to a target https + proxy or endpoint config selector resource. + + Attributes: + name (str): + Required. Name of the ServerTlsPolicy resource. It matches + the pattern + ``projects/*/locations/{location}/serverTlsPolicies/{server_tls_policy}`` + description (str): + Free-text description of the resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was updated. + labels (MutableMapping[str, str]): + Set of label tags associated with the + resource. + allow_open (bool): + Determines if server allows plaintext connections. If set to + true, server allows plain text connections. By default, it + is set to false. This setting is not exclusive of other + encryption modes. For example, if ``allow_open`` and + ``mtls_policy`` are set, server allows both plain text and + mTLS connections. See documentation of other encryption + modes to confirm compatibility. + + Consider using it if you wish to upgrade in place your + deployment to TLS while having mixed TLS and non-TLS traffic + reaching port :80. + server_certificate (google.cloud.network_security_v1beta1.types.CertificateProvider): + Defines a mechanism to provision server identity (public and + private keys). Cannot be combined with ``allow_open`` as a + permissive mode that allows both plain text and TLS is not + supported. + mtls_policy (google.cloud.network_security_v1beta1.types.ServerTlsPolicy.MTLSPolicy): + Defines a mechanism to provision peer validation + certificates for peer to peer authentication (Mutual TLS - + mTLS). If not specified, client certificate will not be + requested. The connection is treated as TLS and not mTLS. If + ``allow_open`` and ``mtls_policy`` are set, server allows + both plain text and mTLS connections. + """ + + class MTLSPolicy(proto.Message): + r"""Specification of the MTLSPolicy. + + Attributes: + client_validation_ca (MutableSequence[google.cloud.network_security_v1beta1.types.ValidationCA]): + Defines the mechanism to obtain the + Certificate Authority certificate to validate + the client certificate. + """ + + client_validation_ca: MutableSequence[tls.ValidationCA] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=tls.ValidationCA, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + allow_open: bool = proto.Field( + proto.BOOL, + number=6, + ) + server_certificate: tls.CertificateProvider = proto.Field( + proto.MESSAGE, + number=7, + message=tls.CertificateProvider, + ) + mtls_policy: MTLSPolicy = proto.Field( + proto.MESSAGE, + number=8, + message=MTLSPolicy, + ) + + +class ListServerTlsPoliciesRequest(proto.Message): + r"""Request used by the ListServerTlsPolicies method. + + Attributes: + parent (str): + Required. The project and location from which the + ServerTlsPolicies should be listed, specified in the format + ``projects/*/locations/{location}``. + page_size (int): + Maximum number of ServerTlsPolicies to return + per call. + page_token (str): + The value returned by the last + ``ListServerTlsPoliciesResponse`` Indicates that this is a + continuation of a prior ``ListServerTlsPolicies`` call, and + that the system should return the next page of data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListServerTlsPoliciesResponse(proto.Message): + r"""Response returned by the ListServerTlsPolicies method. + + Attributes: + server_tls_policies (MutableSequence[google.cloud.network_security_v1beta1.types.ServerTlsPolicy]): + List of ServerTlsPolicy resources. + next_page_token (str): + If there might be 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 + + server_tls_policies: MutableSequence['ServerTlsPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ServerTlsPolicy', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetServerTlsPolicyRequest(proto.Message): + r"""Request used by the GetServerTlsPolicy method. + + Attributes: + name (str): + Required. A name of the ServerTlsPolicy to get. Must be in + the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateServerTlsPolicyRequest(proto.Message): + r"""Request used by the CreateServerTlsPolicy method. + + Attributes: + parent (str): + Required. The parent resource of the ServerTlsPolicy. Must + be in the format ``projects/*/locations/{location}``. + server_tls_policy_id (str): + Required. Short name of the ServerTlsPolicy resource to be + created. This value should be 1-63 characters long, + containing only letters, numbers, hyphens, and underscores, + and should not start with a number. E.g. + "server_mtls_policy". + server_tls_policy (google.cloud.network_security_v1beta1.types.ServerTlsPolicy): + Required. ServerTlsPolicy resource to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + server_tls_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + server_tls_policy: 'ServerTlsPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='ServerTlsPolicy', + ) + + +class UpdateServerTlsPolicyRequest(proto.Message): + r"""Request used by UpdateServerTlsPolicy method. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the ServerTlsPolicy resource by the update. + The fields specified in the update_mask are relative to the + resource, not the full request. A field will be overwritten + if it is in the mask. If the user does not provide a mask + then all fields will be overwritten. + server_tls_policy (google.cloud.network_security_v1beta1.types.ServerTlsPolicy): + Required. Updated ServerTlsPolicy resource. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + server_tls_policy: 'ServerTlsPolicy' = proto.Field( + proto.MESSAGE, + number=2, + message='ServerTlsPolicy', + ) + + +class DeleteServerTlsPolicyRequest(proto.Message): + r"""Request used by the DeleteServerTlsPolicy method. + + Attributes: + name (str): + Required. A name of the ServerTlsPolicy to delete. Must be + in the format + ``projects/*/locations/{location}/serverTlsPolicies/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/tls.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/tls.py new file mode 100644 index 000000000000..df68307eb1c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/tls.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.networksecurity.v1beta1', + manifest={ + 'GrpcEndpoint', + 'ValidationCA', + 'CertificateProviderInstance', + 'CertificateProvider', + }, +) + + +class GrpcEndpoint(proto.Message): + r"""Specification of the GRPC Endpoint. + + Attributes: + target_uri (str): + Required. The target URI of the gRPC + endpoint. Only UDS path is supported, and should + start with "unix:". + """ + + target_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ValidationCA(proto.Message): + r"""Specification of ValidationCA. Defines the mechanism to + obtain the Certificate Authority certificate to validate the + peer certificate. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + grpc_endpoint (google.cloud.network_security_v1beta1.types.GrpcEndpoint): + gRPC specific configuration to access the + gRPC server to obtain the CA certificate. + + This field is a member of `oneof`_ ``type``. + certificate_provider_instance (google.cloud.network_security_v1beta1.types.CertificateProviderInstance): + The certificate provider instance + specification that will be passed to the data + plane, which will be used to load necessary + credential information. + + This field is a member of `oneof`_ ``type``. + """ + + grpc_endpoint: 'GrpcEndpoint' = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message='GrpcEndpoint', + ) + certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( + proto.MESSAGE, + number=3, + oneof='type', + message='CertificateProviderInstance', + ) + + +class CertificateProviderInstance(proto.Message): + r"""Specification of a TLS certificate provider instance. + Workloads may have one or more CertificateProvider instances + (plugins) and one of them is enabled and configured by + specifying this message. Workloads use the values from this + message to locate and load the CertificateProvider instance + configuration. + + Attributes: + plugin_instance (str): + Required. Plugin instance name, used to locate and load + CertificateProvider instance configuration. Set to + "google_cloud_private_spiffe" to use Certificate Authority + Service certificate provider instance. + """ + + plugin_instance: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CertificateProvider(proto.Message): + r"""Specification of certificate provider. Defines the mechanism + to obtain the certificate and private key for peer to peer + authentication. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + grpc_endpoint (google.cloud.network_security_v1beta1.types.GrpcEndpoint): + gRPC specific configuration to access the + gRPC server to obtain the cert and private key. + + This field is a member of `oneof`_ ``type``. + certificate_provider_instance (google.cloud.network_security_v1beta1.types.CertificateProviderInstance): + The certificate provider instance + specification that will be passed to the data + plane, which will be used to load necessary + credential information. + + This field is a member of `oneof`_ ``type``. + """ + + grpc_endpoint: 'GrpcEndpoint' = proto.Field( + proto.MESSAGE, + number=2, + oneof='type', + message='GrpcEndpoint', + ) + certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( + proto.MESSAGE, + number=3, + oneof='type', + message='CertificateProviderInstance', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/mypy.ini b/owl-bot-staging/google-cloud-network-security/v1beta1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/noxfile.py b/owl-bot-staging/google-cloud-network-security/v1beta1/noxfile.py new file mode 100644 index 000000000000..6de174fa4528 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/noxfile.py @@ -0,0 +1,592 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re +import shutil + +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = "google-cloud-network-security" + +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy + "mypy<1.16.0", + "types-requests", + "types-protobuf", + ) + session.install(".") + session.run( + "mypy", + "-p", + "google", + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "update", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "check", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("setuptools", "docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def unit(session, protobuf_implementation): + # Install all test dependencies, then install this package in-place. + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # TODO(https://github.com/googleapis/synthtool/issues/1976): + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +def install_systemtest_dependencies(session, *constraints): + session.install("--pre", "grpcio") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python="3.10") +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.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", ""), + ) + + +@nox.session(python="3.10") +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def prerelease_deps(session, protobuf_implementation): + """ + Run all tests with pre-release versions of dependencies installed + rather than the standard non pre-release versions. + Pre-release versions can be installed using + `pip install --pre `. + """ + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # Note: If a dependency is added to the `prerel_deps` list, + # the `core_dependencies_from_source` list in the `core_deps_from_source` + # nox session should also be updated. + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpc-google-iam-v1", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--ignore-installed", dep) + # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` + # to the dictionary below once this bug is fixed. + # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add + # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below + # once this bug is fixed. + package_namespaces = { + "google-api-core": "google.api_core", + "google-auth": "google.auth", + "grpcio": "grpc", + "protobuf": "google.protobuf", + "proto-plus": "proto", + } + + version_namespace = package_namespaces.get(dep) + + print(f"Installed {dep}") + if version_namespace: + session.run( + "python", + "-c", + f"import {version_namespace}; print({version_namespace}.__version__)", + ) + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb"], +) +def core_deps_from_source(session, protobuf_implementation): + """Run all tests with core dependencies installed from source + rather than pulling the dependencies from PyPI. + """ + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and + # `grpcio-status` should be added to the list below so that they are installed from source, + # rather than PyPI. + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be + # added to the list below so that it is installed from source, rather than PyPI + # Note: If a dependency is added to the `core_dependencies_from_source` list, + # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. + core_dependencies_from_source = [ + "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", + "google-api-core @ git+https://github.com/googleapis/python-api-core.git", + "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", + "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", + "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", + ] + + for dep in core_dependencies_from_source: + session.install(dep, "--no-deps", "--ignore-installed") + print(f"Installed {dep}") + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py new file mode 100644 index 000000000000..3fbd789329cb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_create_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1beta1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1beta1.CreateAuthorizationPolicyRequest( + parent="parent_value", + authorization_policy_id="authorization_policy_id_value", + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.create_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py new file mode 100644 index 000000000000..be56017460a6 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_create_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1beta1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1beta1.CreateAuthorizationPolicyRequest( + parent="parent_value", + authorization_policy_id="authorization_policy_id_value", + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.create_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py new file mode 100644 index 000000000000..4e1421699aad --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1beta1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1beta1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py new file mode 100644 index 000000000000..e66ace52fa5b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_create_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1beta1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1beta1.CreateClientTlsPolicyRequest( + parent="parent_value", + client_tls_policy_id="client_tls_policy_id_value", + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.create_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py new file mode 100644 index 000000000000..d58db9e1cd7b --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_create_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1beta1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1beta1.CreateServerTlsPolicyRequest( + parent="parent_value", + server_tls_policy_id="server_tls_policy_id_value", + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.create_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py new file mode 100644 index 000000000000..df681431f156 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_create_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1beta1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1beta1.CreateServerTlsPolicyRequest( + parent="parent_value", + server_tls_policy_id="server_tls_policy_id_value", + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.create_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py new file mode 100644 index 000000000000..c11cca782530 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_delete_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py new file mode 100644 index 000000000000..0c33c3199057 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_delete_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py new file mode 100644 index 000000000000..6017fdbad8aa --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py new file mode 100644 index 000000000000..c0726eb2d399 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_delete_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py new file mode 100644 index 000000000000..7c31990b7d7a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_delete_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py new file mode 100644 index 000000000000..11e18c3f3760 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_delete_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.DeleteServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py new file mode 100644 index 000000000000..006db5ad1e97 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_get_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_authorization_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py new file mode 100644 index 000000000000..8a6e5d2faaa1 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_get_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetAuthorizationPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_authorization_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py new file mode 100644 index 000000000000..8f0d900d9d38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py new file mode 100644 index 000000000000..5a0e1a6d9193 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_get_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetClientTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_client_tls_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py new file mode 100644 index 000000000000..aa63588350f5 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_get_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_server_tls_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py new file mode 100644 index 000000000000..61a45c8d22ef --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_get_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.GetServerTlsPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_server_tls_policy(request=request) + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py new file mode 100644 index 000000000000..96f5aab5ae6f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAuthorizationPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_list_authorization_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListAuthorizationPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_authorization_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py new file mode 100644 index 000000000000..f1896285f252 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAuthorizationPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_list_authorization_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListAuthorizationPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_authorization_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py new file mode 100644 index 000000000000..8755992dec54 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClientTlsPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py new file mode 100644 index 000000000000..0a925aa6c91a --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListClientTlsPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_list_client_tls_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListClientTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_client_tls_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py new file mode 100644 index 000000000000..3c014a070e38 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServerTlsPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_list_server_tls_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListServerTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_server_tls_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py new file mode 100644 index 000000000000..adc15ffe0772 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServerTlsPolicies +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_list_server_tls_policies(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + request = network_security_v1beta1.ListServerTlsPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_server_tls_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py new file mode 100644 index 000000000000..d25fc6ca2c68 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_update_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1beta1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1beta1.UpdateAuthorizationPolicyRequest( + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.update_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py new file mode 100644 index 000000000000..ad0c06a28f92 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAuthorizationPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_update_authorization_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + authorization_policy = network_security_v1beta1.AuthorizationPolicy() + authorization_policy.name = "name_value" + authorization_policy.action = "DENY" + + request = network_security_v1beta1.UpdateAuthorizationPolicyRequest( + authorization_policy=authorization_policy, + ) + + # Make the request + operation = client.update_authorization_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py new file mode 100644 index 000000000000..17fe7d54e4fb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1beta1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1beta1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py new file mode 100644 index 000000000000..f2cd1e5c4796 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateClientTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_update_client_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + client_tls_policy = network_security_v1beta1.ClientTlsPolicy() + client_tls_policy.name = "name_value" + + request = network_security_v1beta1.UpdateClientTlsPolicyRequest( + client_tls_policy=client_tls_policy, + ) + + # Make the request + operation = client.update_client_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py new file mode 100644 index 000000000000..2700c9392485 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +async def sample_update_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityAsyncClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1beta1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1beta1.UpdateServerTlsPolicyRequest( + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.update_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py new file mode 100644 index 000000000000..39b8be55daa2 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServerTlsPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-network-security + + +# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import network_security_v1beta1 + + +def sample_update_server_tls_policy(): + # Create a client + client = network_security_v1beta1.NetworkSecurityClient() + + # Initialize request argument(s) + server_tls_policy = network_security_v1beta1.ServerTlsPolicy() + server_tls_policy.name = "name_value" + + request = network_security_v1beta1.UpdateServerTlsPolicyRequest( + server_tls_policy=server_tls_policy, + ) + + # Make the request + operation = client.update_server_tls_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json new file mode 100644 index 000000000000..71c9b6489c86 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json @@ -0,0 +1,2502 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.networksecurity.v1beta1", + "version": "v1beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-network-security", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.create_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.CreateAuthorizationPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy" + }, + { + "name": "authorization_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_authorization_policy" + }, + "description": "Sample for CreateAuthorizationPolicy", + "file": "networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.create_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.CreateAuthorizationPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy" + }, + { + "name": "authorization_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_authorization_policy" + }, + "description": "Sample for CreateAuthorizationPolicy", + "file": "networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.create_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.CreateClientTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy" + }, + { + "name": "client_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_client_tls_policy" + }, + "description": "Sample for CreateClientTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.create_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.CreateClientTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy" + }, + { + "name": "client_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_client_tls_policy" + }, + "description": "Sample for CreateClientTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.create_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.CreateServerTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy" + }, + { + "name": "server_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_server_tls_policy" + }, + "description": "Sample for CreateServerTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.create_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.CreateServerTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy" + }, + { + "name": "server_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_server_tls_policy" + }, + "description": "Sample for CreateServerTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.delete_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.DeleteAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_authorization_policy" + }, + "description": "Sample for DeleteAuthorizationPolicy", + "file": "networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.delete_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.DeleteAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_authorization_policy" + }, + "description": "Sample for DeleteAuthorizationPolicy", + "file": "networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.delete_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.DeleteClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_client_tls_policy" + }, + "description": "Sample for DeleteClientTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.delete_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.DeleteClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_client_tls_policy" + }, + "description": "Sample for DeleteClientTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.delete_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.DeleteServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_server_tls_policy" + }, + "description": "Sample for DeleteServerTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.delete_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.DeleteServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_server_tls_policy" + }, + "description": "Sample for DeleteServerTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.get_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.GetAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy", + "shortName": "get_authorization_policy" + }, + "description": "Sample for GetAuthorizationPolicy", + "file": "networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.get_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.GetAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy", + "shortName": "get_authorization_policy" + }, + "description": "Sample for GetAuthorizationPolicy", + "file": "networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.get_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.GetClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy", + "shortName": "get_client_tls_policy" + }, + "description": "Sample for GetClientTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.get_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.GetClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy", + "shortName": "get_client_tls_policy" + }, + "description": "Sample for GetClientTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.get_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.GetServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy", + "shortName": "get_server_tls_policy" + }, + "description": "Sample for GetServerTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.get_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.GetServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy", + "shortName": "get_server_tls_policy" + }, + "description": "Sample for GetServerTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.list_authorization_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListAuthorizationPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListAuthorizationPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager", + "shortName": "list_authorization_policies" + }, + "description": "Sample for ListAuthorizationPolicies", + "file": "networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.list_authorization_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListAuthorizationPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListAuthorizationPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListAuthorizationPoliciesPager", + "shortName": "list_authorization_policies" + }, + "description": "Sample for ListAuthorizationPolicies", + "file": "networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.list_client_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListClientTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListClientTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager", + "shortName": "list_client_tls_policies" + }, + "description": "Sample for ListClientTlsPolicies", + "file": "networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.list_client_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListClientTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListClientTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListClientTlsPoliciesPager", + "shortName": "list_client_tls_policies" + }, + "description": "Sample for ListClientTlsPolicies", + "file": "networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.list_server_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListServerTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListServerTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager", + "shortName": "list_server_tls_policies" + }, + "description": "Sample for ListServerTlsPolicies", + "file": "networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.list_server_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListServerTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListServerTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListServerTlsPoliciesPager", + "shortName": "list_server_tls_policies" + }, + "description": "Sample for ListServerTlsPolicies", + "file": "networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.update_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.UpdateAuthorizationPolicyRequest" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_authorization_policy" + }, + "description": "Sample for UpdateAuthorizationPolicy", + "file": "networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.update_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.UpdateAuthorizationPolicyRequest" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_authorization_policy" + }, + "description": "Sample for UpdateAuthorizationPolicy", + "file": "networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.update_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.UpdateClientTlsPolicyRequest" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_client_tls_policy" + }, + "description": "Sample for UpdateClientTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.update_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.UpdateClientTlsPolicyRequest" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_client_tls_policy" + }, + "description": "Sample for UpdateClientTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.update_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.UpdateServerTlsPolicyRequest" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_server_tls_policy" + }, + "description": "Sample for UpdateServerTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.update_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1beta1.types.UpdateServerTlsPolicyRequest" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_server_tls_policy" + }, + "description": "Sample for UpdateServerTlsPolicy", + "file": "networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/scripts/fixup_network_security_v1beta1_keywords.py b/owl-bot-staging/google-cloud-network-security/v1beta1/scripts/fixup_network_security_v1beta1_keywords.py new file mode 100644 index 000000000000..f383005222af --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/scripts/fixup_network_security_v1beta1_keywords.py @@ -0,0 +1,190 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 network_securityCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_authorization_policy': ('parent', 'authorization_policy_id', 'authorization_policy', ), + 'create_client_tls_policy': ('parent', 'client_tls_policy_id', 'client_tls_policy', ), + 'create_server_tls_policy': ('parent', 'server_tls_policy_id', 'server_tls_policy', ), + 'delete_authorization_policy': ('name', ), + 'delete_client_tls_policy': ('name', ), + 'delete_server_tls_policy': ('name', ), + 'get_authorization_policy': ('name', ), + 'get_client_tls_policy': ('name', ), + 'get_server_tls_policy': ('name', ), + 'list_authorization_policies': ('parent', 'page_size', 'page_token', ), + 'list_client_tls_policies': ('parent', 'page_size', 'page_token', ), + 'list_server_tls_policies': ('parent', 'page_size', 'page_token', ), + 'update_authorization_policy': ('authorization_policy', 'update_mask', ), + 'update_client_tls_policy': ('client_tls_policy', 'update_mask', ), + 'update_server_tls_policy': ('server_tls_policy', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=network_securityCallTransformer(), +): + """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 network_security 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/google-cloud-network-security/v1beta1/setup.py b/owl-bot-staging/google-cloud-network-security/v1beta1/setup.py new file mode 100644 index 000000000000..1f618aa7ad2f --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-network-security' + + +description = "Google Cloud Network Security API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/network_security/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0", + "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", + "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.14.0, <1.0.0", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2010e549cceb --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.13.txt @@ -0,0 +1,12 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +proto-plus>=1 +protobuf>=6 +grpc-google-iam-v1>=0 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..56affbd9bd75 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +grpc-google-iam-v1==0.14.0 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/test_network_security.py b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/test_network_security.py new file mode 100644 index 000000000000..fe8384a82e77 --- /dev/null +++ b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/test_network_security.py @@ -0,0 +1,8936 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.cloud.network_security_v1beta1.services.network_security import NetworkSecurityAsyncClient +from google.cloud.network_security_v1beta1.services.network_security import NetworkSecurityClient +from google.cloud.network_security_v1beta1.services.network_security import pagers +from google.cloud.network_security_v1beta1.services.network_security import transports +from google.cloud.network_security_v1beta1.types import authorization_policy +from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy +from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy +from google.cloud.network_security_v1beta1.types import common +from google.cloud.network_security_v1beta1.types import server_tls_policy +from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy +from google.cloud.network_security_v1beta1.types import tls +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# 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 + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +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 NetworkSecurityClient._get_default_mtls_endpoint(None) is None + assert NetworkSecurityClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert NetworkSecurityClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert NetworkSecurityClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + NetworkSecurityClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + NetworkSecurityClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert NetworkSecurityClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert NetworkSecurityClient._get_client_cert_source(None, False) is None + assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert NetworkSecurityClient._get_client_cert_source(None, True) is mock_default_cert_source + assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE + default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert NetworkSecurityClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT + assert NetworkSecurityClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert NetworkSecurityClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert NetworkSecurityClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert NetworkSecurityClient._get_universe_domain(None, None) == NetworkSecurityClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + NetworkSecurityClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False) +]) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = NetworkSecurityClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + +@pytest.mark.parametrize("error_code", [401,403,404,500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = NetworkSecurityClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + +@pytest.mark.parametrize("client_class,transport_name", [ + (NetworkSecurityClient, "grpc"), + (NetworkSecurityAsyncClient, "grpc_asyncio"), +]) +def test_network_security_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.NetworkSecurityGrpcTransport, "grpc"), + (transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_network_security_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (NetworkSecurityClient, "grpc"), + (NetworkSecurityAsyncClient, "grpc_asyncio"), +]) +def test_network_security_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + ) + + +def test_network_security_client_get_transport_class(): + transport = NetworkSecurityClient.get_transport_class() + available_transports = [ + transports.NetworkSecurityGrpcTransport, + ] + assert transport in available_transports + + transport = NetworkSecurityClient.get_transport_class("grpc") + assert transport == transports.NetworkSecurityGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +def test_network_security_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(NetworkSecurityClient, '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(NetworkSecurityClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "true"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "false"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_network_security_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + NetworkSecurityClient, NetworkSecurityAsyncClient +]) +@mock.patch.object(NetworkSecurityClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityAsyncClient)) +def test_network_security_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # 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) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + NetworkSecurityClient, NetworkSecurityAsyncClient +]) +@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) +@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) +def test_network_security_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE + default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_network_security_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_network_security_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_network_security_client_client_options_from_dict(): + with mock.patch('google.cloud.network_security_v1beta1.services.network_security.transports.NetworkSecurityGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = NetworkSecurityClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_network_security_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "networksecurity.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + authorization_policy.ListAuthorizationPoliciesRequest, + dict, +]) +def test_list_authorization_policies(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_authorization_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = authorization_policy.ListAuthorizationPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthorizationPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_authorization_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = authorization_policy.ListAuthorizationPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_authorization_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == authorization_policy.ListAuthorizationPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_authorization_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_authorization_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_authorization_policies] = mock_rpc + request = {} + client.list_authorization_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_authorization_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_authorization_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_authorization_policies in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_authorization_policies] = mock_rpc + + request = {} + await client.list_authorization_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_authorization_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_authorization_policies_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.ListAuthorizationPoliciesRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_authorization_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = authorization_policy.ListAuthorizationPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthorizationPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_authorization_policies_async_from_dict(): + await test_list_authorization_policies_async(request_type=dict) + +def test_list_authorization_policies_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.ListAuthorizationPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + client.list_authorization_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_authorization_policies_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.ListAuthorizationPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse()) + await client.list_authorization_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_authorization_policies_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_authorization_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_authorization_policies_flattened_error(): + client = NetworkSecurityClient( + 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_authorization_policies( + authorization_policy.ListAuthorizationPoliciesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_authorization_policies_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_authorization_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_authorization_policies_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_authorization_policies( + authorization_policy.ListAuthorizationPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_authorization_policies_pager(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='abc', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[], + next_page_token='def', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='ghi', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_authorization_policies(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, authorization_policy.AuthorizationPolicy) + for i in results) +def test_list_authorization_policies_pages(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='abc', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[], + next_page_token='def', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='ghi', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_authorization_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_list_authorization_policies_async_pager(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='abc', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[], + next_page_token='def', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='ghi', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_authorization_policies(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, authorization_policy.AuthorizationPolicy) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_authorization_policies_async_pages(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='abc', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[], + next_page_token='def', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + ], + next_page_token='ghi', + ), + authorization_policy.ListAuthorizationPoliciesResponse( + authorization_policies=[ + authorization_policy.AuthorizationPolicy(), + authorization_policy.AuthorizationPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_authorization_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + authorization_policy.GetAuthorizationPolicyRequest, + dict, +]) +def test_get_authorization_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.AuthorizationPolicy( + name='name_value', + description='description_value', + action=authorization_policy.AuthorizationPolicy.Action.ALLOW, + ) + response = client.get_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = authorization_policy.GetAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, authorization_policy.AuthorizationPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW + + +def test_get_authorization_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = authorization_policy.GetAuthorizationPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_authorization_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == authorization_policy.GetAuthorizationPolicyRequest( + name='name_value', + ) + +def test_get_authorization_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_authorization_policy] = mock_rpc + request = {} + client.get_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_authorization_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_authorization_policy] = mock_rpc + + request = {} + await client.get_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.GetAuthorizationPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy( + name='name_value', + description='description_value', + action=authorization_policy.AuthorizationPolicy.Action.ALLOW, + )) + response = await client.get_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = authorization_policy.GetAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, authorization_policy.AuthorizationPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW + + +@pytest.mark.asyncio +async def test_get_authorization_policy_async_from_dict(): + await test_get_authorization_policy_async(request_type=dict) + +def test_get_authorization_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.GetAuthorizationPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + call.return_value = authorization_policy.AuthorizationPolicy() + client.get_authorization_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_authorization_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.GetAuthorizationPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy()) + await client.get_authorization_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_authorization_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.AuthorizationPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_authorization_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_authorization_policy_flattened_error(): + client = NetworkSecurityClient( + 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_authorization_policy( + authorization_policy.GetAuthorizationPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_authorization_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = authorization_policy.AuthorizationPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_authorization_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_authorization_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_authorization_policy( + authorization_policy.GetAuthorizationPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_authorization_policy.CreateAuthorizationPolicyRequest, + dict, +]) +def test_create_authorization_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_authorization_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest( + parent='parent_value', + authorization_policy_id='authorization_policy_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_authorization_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_authorization_policy.CreateAuthorizationPolicyRequest( + parent='parent_value', + authorization_policy_id='authorization_policy_id_value', + ) + +def test_create_authorization_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_authorization_policy] = mock_rpc + request = {} + client.create_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_authorization_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_authorization_policy] = mock_rpc + + request = {} + await client.create_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_authorization_policy_async_from_dict(): + await test_create_authorization_policy_async(request_type=dict) + +def test_create_authorization_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_authorization_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_authorization_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_authorization_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_authorization_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_authorization_policy( + parent='parent_value', + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + authorization_policy_id='authorization_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].authorization_policy + mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') + assert arg == mock_val + arg = args[0].authorization_policy_id + mock_val = 'authorization_policy_id_value' + assert arg == mock_val + + +def test_create_authorization_policy_flattened_error(): + client = NetworkSecurityClient( + 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_authorization_policy( + gcn_authorization_policy.CreateAuthorizationPolicyRequest(), + parent='parent_value', + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + authorization_policy_id='authorization_policy_id_value', + ) + +@pytest.mark.asyncio +async def test_create_authorization_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_authorization_policy( + parent='parent_value', + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + authorization_policy_id='authorization_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].authorization_policy + mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') + assert arg == mock_val + arg = args[0].authorization_policy_id + mock_val = 'authorization_policy_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_authorization_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_authorization_policy( + gcn_authorization_policy.CreateAuthorizationPolicyRequest(), + parent='parent_value', + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + authorization_policy_id='authorization_policy_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_authorization_policy.UpdateAuthorizationPolicyRequest, + dict, +]) +def test_update_authorization_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_authorization_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_authorization_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_authorization_policy.UpdateAuthorizationPolicyRequest( + ) + +def test_update_authorization_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_authorization_policy] = mock_rpc + request = {} + client.update_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_authorization_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_authorization_policy] = mock_rpc + + request = {} + await client.update_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_authorization_policy_async_from_dict(): + await test_update_authorization_policy_async(request_type=dict) + +def test_update_authorization_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + request.authorization_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_authorization_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', + 'authorization_policy.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_authorization_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + request.authorization_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_authorization_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', + 'authorization_policy.name=name_value', + ) in kw['metadata'] + + +def test_update_authorization_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_authorization_policy( + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].authorization_policy + mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_authorization_policy_flattened_error(): + client = NetworkSecurityClient( + 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_authorization_policy( + gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_authorization_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_authorization_policy( + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].authorization_policy + mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_authorization_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_authorization_policy( + gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), + authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + authorization_policy.DeleteAuthorizationPolicyRequest, + dict, +]) +def test_delete_authorization_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = authorization_policy.DeleteAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_authorization_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = authorization_policy.DeleteAuthorizationPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_authorization_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == authorization_policy.DeleteAuthorizationPolicyRequest( + name='name_value', + ) + +def test_delete_authorization_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_authorization_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_authorization_policy] = mock_rpc + request = {} + client.delete_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_authorization_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_authorization_policy] = mock_rpc + + request = {} + await client.delete_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_authorization_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.DeleteAuthorizationPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_authorization_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = authorization_policy.DeleteAuthorizationPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_authorization_policy_async_from_dict(): + await test_delete_authorization_policy_async(request_type=dict) + +def test_delete_authorization_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.DeleteAuthorizationPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_authorization_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_authorization_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = authorization_policy.DeleteAuthorizationPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_authorization_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_authorization_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_authorization_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_authorization_policy_flattened_error(): + client = NetworkSecurityClient( + 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_authorization_policy( + authorization_policy.DeleteAuthorizationPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_authorization_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_authorization_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_authorization_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_authorization_policy( + authorization_policy.DeleteAuthorizationPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + server_tls_policy.ListServerTlsPoliciesRequest, + dict, +]) +def test_list_server_tls_policies(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_server_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = server_tls_policy.ListServerTlsPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServerTlsPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_server_tls_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = server_tls_policy.ListServerTlsPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_server_tls_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == server_tls_policy.ListServerTlsPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_server_tls_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_server_tls_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_server_tls_policies] = mock_rpc + request = {} + client.list_server_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_server_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_server_tls_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_server_tls_policies in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_server_tls_policies] = mock_rpc + + request = {} + await client.list_server_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_server_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_server_tls_policies_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.ListServerTlsPoliciesRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_server_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = server_tls_policy.ListServerTlsPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServerTlsPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_server_tls_policies_async_from_dict(): + await test_list_server_tls_policies_async(request_type=dict) + +def test_list_server_tls_policies_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.ListServerTlsPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + client.list_server_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_server_tls_policies_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.ListServerTlsPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse()) + await client.list_server_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_server_tls_policies_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_server_tls_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_server_tls_policies_flattened_error(): + client = NetworkSecurityClient( + 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_server_tls_policies( + server_tls_policy.ListServerTlsPoliciesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_server_tls_policies_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_server_tls_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_server_tls_policies_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_server_tls_policies( + server_tls_policy.ListServerTlsPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_server_tls_policies_pager(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='abc', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[], + next_page_token='def', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='ghi', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_server_tls_policies(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) + for i in results) +def test_list_server_tls_policies_pages(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='abc', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[], + next_page_token='def', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='ghi', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_server_tls_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_list_server_tls_policies_async_pager(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='abc', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[], + next_page_token='def', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='ghi', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_server_tls_policies(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_server_tls_policies_async_pages(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='abc', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[], + next_page_token='def', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + ], + next_page_token='ghi', + ), + server_tls_policy.ListServerTlsPoliciesResponse( + server_tls_policies=[ + server_tls_policy.ServerTlsPolicy(), + server_tls_policy.ServerTlsPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_server_tls_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + server_tls_policy.GetServerTlsPolicyRequest, + dict, +]) +def test_get_server_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ServerTlsPolicy( + name='name_value', + description='description_value', + allow_open=True, + ) + response = client.get_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = server_tls_policy.GetServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, server_tls_policy.ServerTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.allow_open is True + + +def test_get_server_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = server_tls_policy.GetServerTlsPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_server_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == server_tls_policy.GetServerTlsPolicyRequest( + name='name_value', + ) + +def test_get_server_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_server_tls_policy] = mock_rpc + request = {} + client.get_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_server_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_server_tls_policy] = mock_rpc + + request = {} + await client.get_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.GetServerTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy( + name='name_value', + description='description_value', + allow_open=True, + )) + response = await client.get_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = server_tls_policy.GetServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, server_tls_policy.ServerTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.allow_open is True + + +@pytest.mark.asyncio +async def test_get_server_tls_policy_async_from_dict(): + await test_get_server_tls_policy_async(request_type=dict) + +def test_get_server_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.GetServerTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + call.return_value = server_tls_policy.ServerTlsPolicy() + client.get_server_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_server_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.GetServerTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy()) + await client.get_server_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_server_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ServerTlsPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_server_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_server_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_server_tls_policy( + server_tls_policy.GetServerTlsPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_server_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = server_tls_policy.ServerTlsPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_server_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_server_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_server_tls_policy( + server_tls_policy.GetServerTlsPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_server_tls_policy.CreateServerTlsPolicyRequest, + dict, +]) +def test_create_server_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_server_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest( + parent='parent_value', + server_tls_policy_id='server_tls_policy_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_server_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_server_tls_policy.CreateServerTlsPolicyRequest( + parent='parent_value', + server_tls_policy_id='server_tls_policy_id_value', + ) + +def test_create_server_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_server_tls_policy] = mock_rpc + request = {} + client.create_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_server_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_server_tls_policy] = mock_rpc + + request = {} + await client.create_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_server_tls_policy_async_from_dict(): + await test_create_server_tls_policy_async(request_type=dict) + +def test_create_server_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_server_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_server_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_server_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_server_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_server_tls_policy( + parent='parent_value', + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + server_tls_policy_id='server_tls_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].server_tls_policy + mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].server_tls_policy_id + mock_val = 'server_tls_policy_id_value' + assert arg == mock_val + + +def test_create_server_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_server_tls_policy( + gcn_server_tls_policy.CreateServerTlsPolicyRequest(), + parent='parent_value', + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + server_tls_policy_id='server_tls_policy_id_value', + ) + +@pytest.mark.asyncio +async def test_create_server_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_server_tls_policy( + parent='parent_value', + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + server_tls_policy_id='server_tls_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].server_tls_policy + mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].server_tls_policy_id + mock_val = 'server_tls_policy_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_server_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_server_tls_policy( + gcn_server_tls_policy.CreateServerTlsPolicyRequest(), + parent='parent_value', + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + server_tls_policy_id='server_tls_policy_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_server_tls_policy.UpdateServerTlsPolicyRequest, + dict, +]) +def test_update_server_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_server_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_server_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_server_tls_policy.UpdateServerTlsPolicyRequest( + ) + +def test_update_server_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_server_tls_policy] = mock_rpc + request = {} + client.update_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_server_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_server_tls_policy] = mock_rpc + + request = {} + await client.update_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_server_tls_policy_async_from_dict(): + await test_update_server_tls_policy_async(request_type=dict) + +def test_update_server_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + request.server_tls_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_server_tls_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', + 'server_tls_policy.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_server_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + request.server_tls_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_server_tls_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', + 'server_tls_policy.name=name_value', + ) in kw['metadata'] + + +def test_update_server_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_server_tls_policy( + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].server_tls_policy + mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_server_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_server_tls_policy( + gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_server_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_server_tls_policy( + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].server_tls_policy + mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_server_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_server_tls_policy( + gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), + server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + server_tls_policy.DeleteServerTlsPolicyRequest, + dict, +]) +def test_delete_server_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = server_tls_policy.DeleteServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_server_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = server_tls_policy.DeleteServerTlsPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_server_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == server_tls_policy.DeleteServerTlsPolicyRequest( + name='name_value', + ) + +def test_delete_server_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_server_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_server_tls_policy] = mock_rpc + request = {} + client.delete_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_server_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_server_tls_policy] = mock_rpc + + request = {} + await client.delete_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_server_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.DeleteServerTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_server_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = server_tls_policy.DeleteServerTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_async_from_dict(): + await test_delete_server_tls_policy_async(request_type=dict) + +def test_delete_server_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.DeleteServerTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_server_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = server_tls_policy.DeleteServerTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_server_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_server_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_server_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_server_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_server_tls_policy( + server_tls_policy.DeleteServerTlsPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_server_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_server_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_server_tls_policy( + server_tls_policy.DeleteServerTlsPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.ListClientTlsPoliciesRequest, + dict, +]) +def test_list_client_tls_policies(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = client_tls_policy.ListClientTlsPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClientTlsPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_client_tls_policies_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = client_tls_policy.ListClientTlsPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_client_tls_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == client_tls_policy.ListClientTlsPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_client_tls_policies_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_client_tls_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_client_tls_policies] = mock_rpc + request = {} + client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_client_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_client_tls_policies in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_client_tls_policies] = mock_rpc + + request = {} + await client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_client_tls_policies(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.ListClientTlsPoliciesRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_client_tls_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = client_tls_policy.ListClientTlsPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClientTlsPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async_from_dict(): + await test_list_client_tls_policies_async(request_type=dict) + +def test_list_client_tls_policies_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.ListClientTlsPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + client.list_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_client_tls_policies_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.ListClientTlsPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) + await client.list_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_client_tls_policies_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_client_tls_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_client_tls_policies_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policies( + client_tls_policy.ListClientTlsPoliciesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_client_tls_policies_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_client_tls_policies( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_client_tls_policies_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_client_tls_policies( + client_tls_policy.ListClientTlsPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_client_tls_policies_pager(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_client_tls_policies(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) + for i in results) +def test_list_client_tls_policies_pages(transport_name: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_client_tls_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_list_client_tls_policies_async_pager(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_client_tls_policies(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_client_tls_policies_async_pages(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='abc', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[], + next_page_token='def', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + ], + next_page_token='ghi', + ), + client_tls_policy.ListClientTlsPoliciesResponse( + client_tls_policies=[ + client_tls_policy.ClientTlsPolicy(), + client_tls_policy.ClientTlsPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_client_tls_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.GetClientTlsPolicyRequest, + dict, +]) +def test_get_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + ) + response = client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = client_tls_policy.GetClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, client_tls_policy.ClientTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.sni == 'sni_value' + + +def test_get_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = client_tls_policy.GetClientTlsPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == client_tls_policy.GetClientTlsPolicyRequest( + name='name_value', + ) + +def test_get_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_client_tls_policy] = mock_rpc + request = {} + client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_client_tls_policy] = mock_rpc + + request = {} + await client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.GetClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + )) + response = await client.get_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = client_tls_policy.GetClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, client_tls_policy.ClientTlsPolicy) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.sni == 'sni_value' + + +@pytest.mark.asyncio +async def test_get_client_tls_policy_async_from_dict(): + await test_get_client_tls_policy_async(request_type=dict) + +def test_get_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.GetClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value = client_tls_policy.ClientTlsPolicy() + client.get_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.GetClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) + await client.get_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ClientTlsPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + client_tls_policy.GetClientTlsPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = client_tls_policy.ClientTlsPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_client_tls_policy( + client_tls_policy.GetClientTlsPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_client_tls_policy.CreateClientTlsPolicyRequest, + dict, +]) +def test_create_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest( + parent='parent_value', + client_tls_policy_id='client_tls_policy_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_client_tls_policy.CreateClientTlsPolicyRequest( + parent='parent_value', + client_tls_policy_id='client_tls_policy_id_value', + ) + +def test_create_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_client_tls_policy] = mock_rpc + request = {} + client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_client_tls_policy] = mock_rpc + + request = {} + await client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_client_tls_policy_async_from_dict(): + await test_create_client_tls_policy_async(request_type=dict) + +def test_create_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_client_tls_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_client_tls_policy( + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].client_tls_policy_id + mock_val = 'client_tls_policy_id_value' + assert arg == mock_val + + +def test_create_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + gcn_client_tls_policy.CreateClientTlsPolicyRequest(), + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + +@pytest.mark.asyncio +async def test_create_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_client_tls_policy( + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].client_tls_policy_id + mock_val = 'client_tls_policy_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_client_tls_policy( + gcn_client_tls_policy.CreateClientTlsPolicyRequest(), + parent='parent_value', + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + client_tls_policy_id='client_tls_policy_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gcn_client_tls_policy.UpdateClientTlsPolicyRequest, + dict, +]) +def test_update_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcn_client_tls_policy.UpdateClientTlsPolicyRequest( + ) + +def test_update_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_client_tls_policy] = mock_rpc + request = {} + client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_client_tls_policy] = mock_rpc + + request = {} + await client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.update_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_client_tls_policy_async_from_dict(): + await test_update_client_tls_policy_async(request_type=dict) + +def test_update_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + request.client_tls_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_client_tls_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', + 'client_tls_policy.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + request.client_tls_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_client_tls_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', + 'client_tls_policy.name=name_value', + ) in kw['metadata'] + + +def test_update_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_client_tls_policy( + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_client_tls_policy( + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].client_tls_policy + mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_client_tls_policy( + gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), + client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + client_tls_policy.DeleteClientTlsPolicyRequest, + dict, +]) +def test_delete_client_tls_policy(request_type, transport: str = 'grpc'): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = client_tls_policy.DeleteClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_client_tls_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = client_tls_policy.DeleteClientTlsPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_client_tls_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == client_tls_policy.DeleteClientTlsPolicyRequest( + name='name_value', + ) + +def test_delete_client_tls_policy_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_client_tls_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_client_tls_policy] = mock_rpc + request = {} + client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_client_tls_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.delete_client_tls_policy] = mock_rpc + + request = {} + await client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_client_tls_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.DeleteClientTlsPolicyRequest): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_client_tls_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = client_tls_policy.DeleteClientTlsPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_async_from_dict(): + await test_delete_client_tls_policy_async(request_type=dict) + +def test_delete_client_tls_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.DeleteClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = client_tls_policy.DeleteClientTlsPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_client_tls_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_client_tls_policy_flattened(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_client_tls_policy_flattened_error(): + client = NetworkSecurityClient( + 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_client_tls_policy( + client_tls_policy.DeleteClientTlsPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_flattened_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_client_tls_policy( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_client_tls_policy_flattened_error_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_client_tls_policy( + client_tls_policy.DeleteClientTlsPolicyRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = NetworkSecurityClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = NetworkSecurityClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.NetworkSecurityGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.NetworkSecurityGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.NetworkSecurityGrpcTransport, + transports.NetworkSecurityGrpcAsyncIOTransport, +]) +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_kind_grpc(): + transport = NetworkSecurityClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_authorization_policies_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() + client.list_authorization_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.ListAuthorizationPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + call.return_value = authorization_policy.AuthorizationPolicy() + client.get_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.GetAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_authorization_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_server_tls_policies_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() + client.list_server_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.ListServerTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + call.return_value = server_tls_policy.ServerTlsPolicy() + client.get_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.GetServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_server_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_client_tls_policies_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() + client.list_client_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.ListClientTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + call.return_value = client_tls_policy.ClientTlsPolicy() + client.get_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.GetClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_client_tls_policy_empty_call_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = NetworkSecurityAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_authorization_policies_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_authorization_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse( + next_page_token='next_page_token_value', + )) + await client.list_authorization_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.ListAuthorizationPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy( + name='name_value', + description='description_value', + action=authorization_policy.AuthorizationPolicy.Action.ALLOW, + )) + await client.get_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.GetAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_authorization_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_authorization_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_authorization_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_server_tls_policies_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_server_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse( + next_page_token='next_page_token_value', + )) + await client.list_server_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.ListServerTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy( + name='name_value', + description='description_value', + allow_open=True, + )) + await client.get_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.GetServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_server_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_server_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_server_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_client_tls_policies_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_client_tls_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( + next_page_token='next_page_token_value', + )) + await client.list_client_tls_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.ListClientTlsPoliciesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( + name='name_value', + description='description_value', + sni='sni_value', + )) + await client.get_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.GetClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.update_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_client_tls_policy_empty_call_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_client_tls_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.delete_client_tls_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.NetworkSecurityGrpcTransport, + ) + +def test_network_security_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.NetworkSecurityTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_network_security_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.network_security_v1beta1.services.network_security.transports.NetworkSecurityTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.NetworkSecurityTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_authorization_policies', + 'get_authorization_policy', + 'create_authorization_policy', + 'update_authorization_policy', + 'delete_authorization_policy', + 'list_server_tls_policies', + 'get_server_tls_policy', + 'create_server_tls_policy', + 'update_server_tls_policy', + 'delete_server_tls_policy', + 'list_client_tls_policies', + 'get_client_tls_policy', + 'create_client_tls_policy', + 'update_client_tls_policy', + 'delete_client_tls_policy', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + 'cancel_operation', + 'delete_operation', + 'list_operations', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_network_security_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.network_security_v1beta1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkSecurityTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +def test_network_security_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.network_security_v1beta1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.NetworkSecurityTransport() + adc.assert_called_once() + + +def test_network_security_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) + NetworkSecurityClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.NetworkSecurityGrpcTransport, + transports.NetworkSecurityGrpcAsyncIOTransport, + ], +) +def test_network_security_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.NetworkSecurityGrpcTransport, + transports.NetworkSecurityGrpcAsyncIOTransport, + ], +) +def test_network_security_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.NetworkSecurityGrpcTransport, grpc_helpers), + (transports.NetworkSecurityGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_network_security_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( + "networksecurity.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="networksecurity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) +def test_network_security_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_network_security_host_no_port(transport_name): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networksecurity.googleapis.com:443' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", +]) +def test_network_security_host_with_port(transport_name): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'networksecurity.googleapis.com:8000' + ) + +def test_network_security_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NetworkSecurityGrpcTransport( + 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_network_security_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.NetworkSecurityGrpcAsyncIOTransport( + 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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) +def test_network_security_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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) +def test_network_security_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_network_security_grpc_lro_client(): + client = NetworkSecurityClient( + 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_network_security_grpc_lro_async_client(): + client = NetworkSecurityAsyncClient( + 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_authorization_policy_path(): + project = "squid" + location = "clam" + authorization_policy = "whelk" + expected = "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format(project=project, location=location, authorization_policy=authorization_policy, ) + actual = NetworkSecurityClient.authorization_policy_path(project, location, authorization_policy) + assert expected == actual + + +def test_parse_authorization_policy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "authorization_policy": "nudibranch", + } + path = NetworkSecurityClient.authorization_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_authorization_policy_path(path) + assert expected == actual + +def test_client_tls_policy_path(): + project = "cuttlefish" + location = "mussel" + client_tls_policy = "winkle" + expected = "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) + actual = NetworkSecurityClient.client_tls_policy_path(project, location, client_tls_policy) + assert expected == actual + + +def test_parse_client_tls_policy_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "client_tls_policy": "abalone", + } + path = NetworkSecurityClient.client_tls_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_client_tls_policy_path(path) + assert expected == actual + +def test_server_tls_policy_path(): + project = "squid" + location = "clam" + server_tls_policy = "whelk" + expected = "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format(project=project, location=location, server_tls_policy=server_tls_policy, ) + actual = NetworkSecurityClient.server_tls_policy_path(project, location, server_tls_policy) + assert expected == actual + + +def test_parse_server_tls_policy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "server_tls_policy": "nudibranch", + } + path = NetworkSecurityClient.server_tls_policy_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_server_tls_policy_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = NetworkSecurityClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = NetworkSecurityClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = NetworkSecurityClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = NetworkSecurityClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = NetworkSecurityClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = NetworkSecurityClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = NetworkSecurityClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = NetworkSecurityClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = NetworkSecurityClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = NetworkSecurityClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = NetworkSecurityClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: + transport_class = NetworkSecurityClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_delete_operation_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + +def test_cancel_operation_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_cancel_operation_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = NetworkSecurityAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = NetworkSecurityClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport), + (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From deb43b2b31e0896f3d2d14758265c61677ed4ca8 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 2 Sep 2025 16:03:46 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../v1/.coveragerc | 13 - .../google-cloud-network-security/v1/.flake8 | 34 - .../google-cloud-network-security/v1/LICENSE | 202 - .../v1/MANIFEST.in | 20 - .../v1/README.rst | 143 - .../v1/docs/_static/custom.css | 20 - .../v1/docs/_templates/layout.html | 50 - .../v1/docs/conf.py | 385 - .../v1/docs/index.rst | 10 - .../v1/docs/multiprocessing.rst | 7 - .../network_security_v1/network_security.rst | 10 - .../v1/docs/network_security_v1/services_.rst | 8 - .../v1/docs/network_security_v1/types_.rst | 6 - .../google/cloud/network_security/__init__.py | 111 - .../cloud/network_security/gapic_version.py | 16 - .../v1/google/cloud/network_security/py.typed | 2 - .../cloud/network_security_v1/__init__.py | 112 - .../network_security_v1/gapic_metadata.json | 561 - .../network_security_v1/gapic_version.py | 16 - .../google/cloud/network_security_v1/py.typed | 2 - .../network_security_v1/services/__init__.py | 15 - .../services/network_security/__init__.py | 22 - .../services/network_security/async_client.py | 2866 --- .../services/network_security/client.py | 3253 ---- .../services/network_security/pagers.py | 446 - .../network_security/transports/README.rst | 9 - .../network_security/transports/__init__.py | 38 - .../network_security/transports/base.py | 497 - .../network_security/transports/grpc.py | 933 - .../transports/grpc_asyncio.py | 1069 -- .../network_security/transports/rest.py | 4105 ----- .../network_security/transports/rest_base.py | 1036 -- .../network_security_v1/types/__init__.py | 106 - .../types/authorization_policy.py | 425 - .../types/client_tls_policy.py | 271 - .../cloud/network_security_v1/types/common.py | 95 - .../types/network_security.py | 26 - .../types/server_tls_policy.py | 296 - .../cloud/network_security_v1/types/tls.py | 154 - .../google-cloud-network-security/v1/mypy.ini | 3 - .../v1/noxfile.py | 592 - ...urity_create_authorization_policy_async.py | 62 - ...curity_create_authorization_policy_sync.py | 62 - ...security_create_client_tls_policy_async.py | 61 - ..._security_create_client_tls_policy_sync.py | 61 - ...security_create_server_tls_policy_async.py | 61 - ..._security_create_server_tls_policy_sync.py | 61 - ...urity_delete_authorization_policy_async.py | 56 - ...curity_delete_authorization_policy_sync.py | 56 - ...security_delete_client_tls_policy_async.py | 56 - ..._security_delete_client_tls_policy_sync.py | 56 - ...security_delete_server_tls_policy_async.py | 56 - ..._security_delete_server_tls_policy_sync.py | 56 - ...security_get_authorization_policy_async.py | 52 - ..._security_get_authorization_policy_sync.py | 52 - ...rk_security_get_client_tls_policy_async.py | 52 - ...ork_security_get_client_tls_policy_sync.py | 52 - ...rk_security_get_server_tls_policy_async.py | 52 - ...ork_security_get_server_tls_policy_sync.py | 52 - ...urity_list_authorization_policies_async.py | 53 - ...curity_list_authorization_policies_sync.py | 53 - ...security_list_client_tls_policies_async.py | 53 - ..._security_list_client_tls_policies_sync.py | 53 - ...security_list_server_tls_policies_async.py | 53 - ..._security_list_server_tls_policies_sync.py | 53 - ...urity_update_authorization_policy_async.py | 60 - ...curity_update_authorization_policy_sync.py | 60 - ...security_update_client_tls_policy_async.py | 59 - ..._security_update_client_tls_policy_sync.py | 59 - ...security_update_server_tls_policy_async.py | 59 - ..._security_update_server_tls_policy_sync.py | 59 - ...adata_google.cloud.networksecurity.v1.json | 5496 ------ .../fixup_network_security_v1_keywords.py | 199 - .../google-cloud-network-security/v1/setup.py | 99 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.13.txt | 12 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../gapic/network_security_v1/__init__.py | 16 - .../test_network_security.py | 14565 ---------------- .../v1alpha1/.coveragerc | 13 - .../v1alpha1/.flake8 | 34 - .../v1alpha1/LICENSE | 202 - .../v1alpha1/MANIFEST.in | 20 - .../v1alpha1/README.rst | 143 - .../v1alpha1/docs/_static/custom.css | 20 - .../v1alpha1/docs/_templates/layout.html | 50 - .../v1alpha1/docs/conf.py | 385 - .../v1alpha1/docs/index.rst | 10 - .../v1alpha1/docs/multiprocessing.rst | 7 - .../network_security.rst | 10 - .../network_security_v1alpha1/services_.rst | 6 - .../docs/network_security_v1alpha1/types_.rst | 6 - .../google/cloud/network_security/__init__.py | 51 - .../cloud/network_security/gapic_version.py | 16 - .../google/cloud/network_security/py.typed | 2 - .../network_security_v1alpha1/__init__.py | 52 - .../gapic_metadata.json | 103 - .../gapic_version.py | 16 - .../cloud/network_security_v1alpha1/py.typed | 2 - .../services/__init__.py | 15 - .../services/network_security/__init__.py | 22 - .../services/network_security/async_client.py | 1539 -- .../services/network_security/client.py | 1918 -- .../services/network_security/pagers.py | 166 - .../network_security/transports/README.rst | 9 - .../network_security/transports/__init__.py | 38 - .../network_security/transports/base.py | 353 - .../network_security/transports/grpc.py | 664 - .../transports/grpc_asyncio.py | 750 - .../network_security/transports/rest.py | 2341 --- .../network_security/transports/rest_base.py | 614 - .../types/__init__.py | 48 - .../types/client_tls_policy.py | 271 - .../network_security_v1alpha1/types/common.py | 95 - .../types/network_security.py | 26 - .../network_security_v1alpha1/types/tls.py | 197 - .../v1alpha1/mypy.ini | 3 - .../v1alpha1/noxfile.py | 592 - ...security_create_client_tls_policy_async.py | 61 - ..._security_create_client_tls_policy_sync.py | 61 - ...security_delete_client_tls_policy_async.py | 56 - ..._security_delete_client_tls_policy_sync.py | 56 - ...rk_security_get_client_tls_policy_async.py | 52 - ...ork_security_get_client_tls_policy_sync.py | 52 - ...security_list_client_tls_policies_async.py | 53 - ..._security_list_client_tls_policies_sync.py | 53 - ...security_update_client_tls_policy_async.py | 59 - ..._security_update_client_tls_policy_sync.py | 59 - ...google.cloud.networksecurity.v1alpha1.json | 844 - ...ixup_network_security_v1alpha1_keywords.py | 180 - .../v1alpha1/setup.py | 99 - .../v1alpha1/testing/constraints-3.10.txt | 7 - .../v1alpha1/testing/constraints-3.11.txt | 7 - .../v1alpha1/testing/constraints-3.12.txt | 7 - .../v1alpha1/testing/constraints-3.13.txt | 12 - .../v1alpha1/testing/constraints-3.7.txt | 11 - .../v1alpha1/testing/constraints-3.8.txt | 7 - .../v1alpha1/testing/constraints-3.9.txt | 7 - .../v1alpha1/tests/__init__.py | 16 - .../v1alpha1/tests/unit/__init__.py | 16 - .../v1alpha1/tests/unit/gapic/__init__.py | 16 - .../network_security_v1alpha1/__init__.py | 16 - .../test_network_security.py | 7023 -------- .../v1beta1/.coveragerc | 13 - .../v1beta1/.flake8 | 34 - .../v1beta1/LICENSE | 202 - .../v1beta1/MANIFEST.in | 20 - .../v1beta1/README.rst | 143 - .../v1beta1/docs/_static/custom.css | 20 - .../v1beta1/docs/_templates/layout.html | 50 - .../v1beta1/docs/conf.py | 385 - .../v1beta1/docs/index.rst | 10 - .../v1beta1/docs/multiprocessing.rst | 7 - .../network_security.rst | 10 - .../network_security_v1beta1/services_.rst | 6 - .../docs/network_security_v1beta1/types_.rst | 6 - .../google/cloud/network_security/__init__.py | 79 - .../cloud/network_security/gapic_version.py | 16 - .../google/cloud/network_security/py.typed | 2 - .../network_security_v1beta1/__init__.py | 80 - .../gapic_metadata.json | 173 - .../network_security_v1beta1/gapic_version.py | 16 - .../cloud/network_security_v1beta1/py.typed | 2 - .../services/__init__.py | 15 - .../services/network_security/__init__.py | 22 - .../services/network_security/async_client.py | 2866 --- .../services/network_security/client.py | 3251 ---- .../services/network_security/pagers.py | 446 - .../network_security/transports/README.rst | 9 - .../network_security/transports/__init__.py | 33 - .../network_security/transports/base.py | 497 - .../network_security/transports/grpc.py | 933 - .../transports/grpc_asyncio.py | 1069 -- .../types/__init__.py | 80 - .../types/authorization_policy.py | 425 - .../types/client_tls_policy.py | 271 - .../network_security_v1beta1/types/common.py | 95 - .../types/network_security.py | 26 - .../types/server_tls_policy.py | 296 - .../network_security_v1beta1/types/tls.py | 154 - .../v1beta1/mypy.ini | 3 - .../v1beta1/noxfile.py | 592 - ...urity_create_authorization_policy_async.py | 62 - ...curity_create_authorization_policy_sync.py | 62 - ...security_create_client_tls_policy_async.py | 61 - ..._security_create_client_tls_policy_sync.py | 61 - ...security_create_server_tls_policy_async.py | 61 - ..._security_create_server_tls_policy_sync.py | 61 - ...urity_delete_authorization_policy_async.py | 56 - ...curity_delete_authorization_policy_sync.py | 56 - ...security_delete_client_tls_policy_async.py | 56 - ..._security_delete_client_tls_policy_sync.py | 56 - ...security_delete_server_tls_policy_async.py | 56 - ..._security_delete_server_tls_policy_sync.py | 56 - ...security_get_authorization_policy_async.py | 52 - ..._security_get_authorization_policy_sync.py | 52 - ...rk_security_get_client_tls_policy_async.py | 52 - ...ork_security_get_client_tls_policy_sync.py | 52 - ...rk_security_get_server_tls_policy_async.py | 52 - ...ork_security_get_server_tls_policy_sync.py | 52 - ...urity_list_authorization_policies_async.py | 53 - ...curity_list_authorization_policies_sync.py | 53 - ...security_list_client_tls_policies_async.py | 53 - ..._security_list_client_tls_policies_sync.py | 53 - ...security_list_server_tls_policies_async.py | 53 - ..._security_list_server_tls_policies_sync.py | 53 - ...urity_update_authorization_policy_async.py | 60 - ...curity_update_authorization_policy_sync.py | 60 - ...security_update_client_tls_policy_async.py | 59 - ..._security_update_client_tls_policy_sync.py | 59 - ...security_update_server_tls_policy_async.py | 59 - ..._security_update_server_tls_policy_sync.py | 59 - ..._google.cloud.networksecurity.v1beta1.json | 2502 --- ...fixup_network_security_v1beta1_keywords.py | 190 - .../v1beta1/setup.py | 99 - .../v1beta1/testing/constraints-3.10.txt | 7 - .../v1beta1/testing/constraints-3.11.txt | 7 - .../v1beta1/testing/constraints-3.12.txt | 7 - .../v1beta1/testing/constraints-3.13.txt | 12 - .../v1beta1/testing/constraints-3.7.txt | 11 - .../v1beta1/testing/constraints-3.8.txt | 7 - .../v1beta1/testing/constraints-3.9.txt | 7 - .../v1beta1/tests/__init__.py | 16 - .../v1beta1/tests/unit/__init__.py | 16 - .../v1beta1/tests/unit/gapic/__init__.py | 16 - .../network_security_v1beta1/__init__.py | 16 - .../test_network_security.py | 8936 ---------- .../address_group_service.rst | 0 .../organization_address_group_service.rst | 0 .../docs/network_security_v1/services_.rst | 2 + .../google/cloud/network_security/__init__.py | 42 + .../cloud/network_security_v1/__init__.py | 38 + .../network_security_v1/gapic_metadata.json | 308 + .../address_group_service/__init__.py | 6 +- .../address_group_service/async_client.py | 568 +- .../services/address_group_service/client.py | 704 +- .../services/address_group_service}/pagers.py | 152 +- .../transports/README.rst | 0 .../transports/__init__.py | 24 +- .../address_group_service/transports/base.py | 233 +- .../address_group_service/transports/grpc.py | 274 +- .../transports/grpc_asyncio.py | 291 +- .../address_group_service/transports/rest.py | 2236 ++- .../transports/rest_base.py | 689 +- .../network_security/transports/rest.py | 17 + .../network_security/transports/rest_base.py | 53 + .../__init__.py | 6 +- .../async_client.py | 593 +- .../client.py | 731 +- .../pagers.py | 152 +- .../transports/README.rst | 0 .../transports/__init__.py | 29 +- .../transports/base.py | 233 +- .../transports/grpc.py | 278 +- .../transports/grpc_asyncio.py | 295 +- .../transports/rest.py | 2266 ++- .../transports/rest_base.py | 693 +- .../network_security_v1/types/__init__.py | 26 + .../types/address_group.py | 47 +- ...p_service_add_address_group_items_async.py | 0 ...up_service_add_address_group_items_sync.py | 0 ...service_clone_address_group_items_async.py | 0 ..._service_clone_address_group_items_sync.py | 0 ...roup_service_create_address_group_async.py | 0 ...group_service_create_address_group_sync.py | 0 ...roup_service_delete_address_group_async.py | 0 ...group_service_delete_address_group_sync.py | 0 ...s_group_service_get_address_group_async.py | 0 ...ss_group_service_get_address_group_sync.py | 0 ...ice_list_address_group_references_async.py | 0 ...vice_list_address_group_references_sync.py | 0 ...group_service_list_address_groups_async.py | 0 ..._group_service_list_address_groups_sync.py | 0 ...ervice_remove_address_group_items_async.py | 0 ...service_remove_address_group_items_sync.py | 0 ...roup_service_update_address_group_async.py | 0 ...group_service_update_address_group_sync.py | 0 ...p_service_add_address_group_items_async.py | 0 ...up_service_add_address_group_items_sync.py | 0 ...service_clone_address_group_items_async.py | 0 ..._service_clone_address_group_items_sync.py | 0 ...roup_service_create_address_group_async.py | 0 ...group_service_create_address_group_sync.py | 0 ...roup_service_delete_address_group_async.py | 0 ...group_service_delete_address_group_sync.py | 0 ...s_group_service_get_address_group_async.py | 0 ...ss_group_service_get_address_group_sync.py | 0 ...ice_list_address_group_references_async.py | 0 ...vice_list_address_group_references_sync.py | 0 ...group_service_list_address_groups_async.py | 0 ..._group_service_list_address_groups_sync.py | 0 ...ervice_remove_address_group_items_async.py | 0 ...service_remove_address_group_items_sync.py | 0 ...roup_service_update_address_group_async.py | 0 ...group_service_update_address_group_sync.py | 0 ...adata_google.cloud.networksecurity.v1.json | 4242 ++++- .../fixup_network_security_v1_keywords.py | 9 + .../test_address_group_service.py | 5244 ++++-- ...test_organization_address_group_service.py | 5344 ++++-- 306 files changed, 17533 insertions(+), 93983 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/LICENSE delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/_templates/layout.html delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/multiprocessing.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/network_security.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/async_client.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/client.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/pagers.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/authorization_policy.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/client_tls_policy.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/common.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/network_security.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/server_tls_policy.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/tls.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/scripts/fixup_network_security_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_network_security.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/LICENSE delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_templates/layout.html delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/multiprocessing.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/network_security.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/async_client.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/client.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/pagers.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/client_tls_policy.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/common.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/network_security.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/tls.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/scripts/fixup_network_security_v1alpha1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/setup.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/test_network_security.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/LICENSE delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/_templates/layout.html delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/multiprocessing.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/network_security.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/py.typed delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/async_client.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/client.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/pagers.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/authorization_policy.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/client_tls_policy.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/common.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/network_security.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/server_tls_policy.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/tls.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/scripts/fixup_network_security_v1beta1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/setup.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/test_network_security.py rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/docs/network_security_v1/address_group_service.rst (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/docs/network_security_v1/organization_address_group_service.rst (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/address_group_service/__init__.py (91%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/address_group_service/async_client.py (85%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/address_group_service/client.py (84%) rename {owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service => packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service}/pagers.py (76%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/address_group_service/transports/README.rst (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py (60%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/address_group_service/transports/base.py (69%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py (82%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py (83%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/address_group_service/transports/rest.py (65%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py (52%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py (88%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py (84%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/organization_address_group_service/client.py (83%) rename {owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service => packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service}/pagers.py (76%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/organization_address_group_service/transports/README.rst (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py (56%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py (69%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py (81%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py (82%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py (65%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py (51%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/google/cloud/network_security_v1/types/address_group.py (95%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py (100%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/tests/unit/gapic/network_security_v1/test_address_group_service.py (72%) rename {owl-bot-staging/google-cloud-network-security/v1 => packages/google-cloud-network-security}/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py (72%) diff --git a/owl-bot-staging/google-cloud-network-security/v1/.coveragerc b/owl-bot-staging/google-cloud-network-security/v1/.coveragerc deleted file mode 100644 index ed01d62f0f9a..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/network_security/__init__.py - google/cloud/network_security/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-network-security/v1/.flake8 b/owl-bot-staging/google-cloud-network-security/v1/.flake8 deleted file mode 100644 index 90316de21489..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/.flake8 +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -[flake8] -# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): -# Resolve flake8 lint issues -ignore = E203, E231, E266, E501, W503 -exclude = - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): - # Ensure that generated code passes flake8 lint - **/gapic/** - **/services/** - **/types/** - # Exclude Protobuf gencode - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/LICENSE b/owl-bot-staging/google-cloud-network-security/v1/LICENSE deleted file mode 100644 index d64569567334..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/google-cloud-network-security/v1/MANIFEST.in b/owl-bot-staging/google-cloud-network-security/v1/MANIFEST.in deleted file mode 100644 index dae249ec8976..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/MANIFEST.in +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -include README.rst LICENSE -recursive-include google *.py *.pyi *.json *.proto py.typed -recursive-include tests * -global-exclude *.py[co] -global-exclude __pycache__ diff --git a/owl-bot-staging/google-cloud-network-security/v1/README.rst b/owl-bot-staging/google-cloud-network-security/v1/README.rst deleted file mode 100644 index fed4f0a4d3c6..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Cloud Network Security 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 Network Security 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 - - -Logging -------- - -This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. -Note the following: - -#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. -#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. -#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. - - -Simple, environment-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google -logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged -messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging -event. - -A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. - -- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. -- Invalid logging scopes: :code:`foo`, :code:`123`, etc. - -**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. - - -Examples -^^^^^^^^ - -- Enabling the default handler for all Google-based loggers - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google - -- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 - - -Advanced, code-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can also configure a valid logging scope using Python's standard `logging` mechanism. - - -Examples -^^^^^^^^ - -- Configuring a handler for all Google-based loggers - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - -- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google.cloud.library_v1") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - - -Logging details -~~~~~~~~~~~~~~~ - -#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root - logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set - :code:`logging.getLogger("google").propagate = True` in your code. -#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for - one library, but decide you need to also set up environment-based logging configuration for another library. - - #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual - if the code -based configuration gets applied first. - -#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get - executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. - (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-security/v1/docs/_static/custom.css deleted file mode 100644 index b0a295464b23..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/docs/_static/custom.css +++ /dev/null @@ -1,20 +0,0 @@ -div#python2-eol { - border-color: red; - border-width: medium; -} - -/* Ensure minimum width for 'Parameters' / 'Returns' column */ -dl.field-list > dt { - min-width: 100px -} - -/* Insert space between methods for readability */ -dl.method { - padding-top: 10px; - padding-bottom: 10px -} - -/* Insert empty space between classes */ -dl.class { - padding-bottom: 50px -} diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/_templates/layout.html b/owl-bot-staging/google-cloud-network-security/v1/docs/_templates/layout.html deleted file mode 100644 index 95e9c77fcfe1..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/docs/_templates/layout.html +++ /dev/null @@ -1,50 +0,0 @@ - -{% extends "!layout.html" %} -{%- block content %} -{%- if theme_fixed_sidebar|lower == 'true' %} -
- {{ sidebar() }} - {%- block document %} -
- {%- if render_sidebar %} -
- {%- endif %} - - {%- block relbar_top %} - {%- if theme_show_relbar_top|tobool %} - - {%- endif %} - {% endblock %} - -
-
- As of January 1, 2020 this library no longer supports Python 2 on the latest released version. - Library versions released prior to that date will continue to be available. For more information please - visit Python 2 support on Google Cloud. -
- {% block body %} {% endblock %} -
- - {%- block relbar_bottom %} - {%- if theme_show_relbar_bottom|tobool %} - - {%- endif %} - {% endblock %} - - {%- if render_sidebar %} -
- {%- endif %} -
- {%- endblock %} -
-
-{%- else %} -{{ super() }} -{%- endif %} -{%- endblock %} diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/conf.py b/owl-bot-staging/google-cloud-network-security/v1/docs/conf.py deleted file mode 100644 index cf26b0443b74..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/docs/conf.py +++ /dev/null @@ -1,385 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-network-security 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("..")) - -# For plugins that can not read conf.py. -# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 -sys.path.insert(0, os.path.abspath(".")) - -__version__ = "" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.5.0" - -# 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.doctest", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", - "recommonmark", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_options = {"members": True} -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# source_suffix = ['.rst', '.md'] -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-network-security" -copyright = u"2025, Google, LLC" -author = u"Google APIs" - -# 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", - "**/.nox/**/*", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/README.rst", -] - -# 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 google-cloud-network-security", - "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-network-security-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-network-security.tex", - u"google-cloud-network-security Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-network-security", - "google-cloud-network-security Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-network-security", - "google-cloud-network-security Documentation", - author, - "google-cloud-network-security", - "google-cloud-network-security Library", - "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": ("https://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), - "google.api_core": ( - "https://googleapis.dev/python/google-api-core/latest/", - None, - ), - "grpc": ("https://grpc.github.io/grpc/python/", None), - "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", 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/google-cloud-network-security/v1/docs/index.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/index.rst deleted file mode 100644 index 84467baeb84a..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/docs/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. include:: multiprocessing.rst - - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - network_security_v1/services_ - network_security_v1/types_ diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/multiprocessing.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/multiprocessing.rst deleted file mode 100644 index 536d17b2ea65..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/docs/multiprocessing.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. note:: - - Because this client uses :mod:`grpc` library, it is safe to - share instances across threads. In multiprocessing scenarios, the best - practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.pool.Pool` or - :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/network_security.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/network_security.rst deleted file mode 100644 index aa99d3fc659b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/network_security.rst +++ /dev/null @@ -1,10 +0,0 @@ -NetworkSecurity ---------------------------------- - -.. automodule:: google.cloud.network_security_v1.services.network_security - :members: - :inherited-members: - -.. automodule:: google.cloud.network_security_v1.services.network_security.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/services_.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/services_.rst deleted file mode 100644 index a78574643ed1..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/services_.rst +++ /dev/null @@ -1,8 +0,0 @@ -Services for Google Cloud Network Security v1 API -================================================= -.. toctree:: - :maxdepth: 2 - - address_group_service - network_security - organization_address_group_service diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/types_.rst b/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/types_.rst deleted file mode 100644 index 61c840bc8d6f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Network Security v1 API -============================================== - -.. automodule:: google.cloud.network_security_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/__init__.py deleted file mode 100644 index 4b235ebcb40e..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/__init__.py +++ /dev/null @@ -1,111 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.network_security import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.network_security_v1.services.address_group_service.client import AddressGroupServiceClient -from google.cloud.network_security_v1.services.address_group_service.async_client import AddressGroupServiceAsyncClient -from google.cloud.network_security_v1.services.network_security.client import NetworkSecurityClient -from google.cloud.network_security_v1.services.network_security.async_client import NetworkSecurityAsyncClient -from google.cloud.network_security_v1.services.organization_address_group_service.client import OrganizationAddressGroupServiceClient -from google.cloud.network_security_v1.services.organization_address_group_service.async_client import OrganizationAddressGroupServiceAsyncClient - -from google.cloud.network_security_v1.types.address_group import AddAddressGroupItemsRequest -from google.cloud.network_security_v1.types.address_group import AddressGroup -from google.cloud.network_security_v1.types.address_group import CloneAddressGroupItemsRequest -from google.cloud.network_security_v1.types.address_group import CreateAddressGroupRequest -from google.cloud.network_security_v1.types.address_group import DeleteAddressGroupRequest -from google.cloud.network_security_v1.types.address_group import GetAddressGroupRequest -from google.cloud.network_security_v1.types.address_group import ListAddressGroupReferencesRequest -from google.cloud.network_security_v1.types.address_group import ListAddressGroupReferencesResponse -from google.cloud.network_security_v1.types.address_group import ListAddressGroupsRequest -from google.cloud.network_security_v1.types.address_group import ListAddressGroupsResponse -from google.cloud.network_security_v1.types.address_group import RemoveAddressGroupItemsRequest -from google.cloud.network_security_v1.types.address_group import UpdateAddressGroupRequest -from google.cloud.network_security_v1.types.authorization_policy import AuthorizationPolicy -from google.cloud.network_security_v1.types.authorization_policy import CreateAuthorizationPolicyRequest -from google.cloud.network_security_v1.types.authorization_policy import DeleteAuthorizationPolicyRequest -from google.cloud.network_security_v1.types.authorization_policy import GetAuthorizationPolicyRequest -from google.cloud.network_security_v1.types.authorization_policy import ListAuthorizationPoliciesRequest -from google.cloud.network_security_v1.types.authorization_policy import ListAuthorizationPoliciesResponse -from google.cloud.network_security_v1.types.authorization_policy import UpdateAuthorizationPolicyRequest -from google.cloud.network_security_v1.types.client_tls_policy import ClientTlsPolicy -from google.cloud.network_security_v1.types.client_tls_policy import CreateClientTlsPolicyRequest -from google.cloud.network_security_v1.types.client_tls_policy import DeleteClientTlsPolicyRequest -from google.cloud.network_security_v1.types.client_tls_policy import GetClientTlsPolicyRequest -from google.cloud.network_security_v1.types.client_tls_policy import ListClientTlsPoliciesRequest -from google.cloud.network_security_v1.types.client_tls_policy import ListClientTlsPoliciesResponse -from google.cloud.network_security_v1.types.client_tls_policy import UpdateClientTlsPolicyRequest -from google.cloud.network_security_v1.types.common import OperationMetadata -from google.cloud.network_security_v1.types.server_tls_policy import CreateServerTlsPolicyRequest -from google.cloud.network_security_v1.types.server_tls_policy import DeleteServerTlsPolicyRequest -from google.cloud.network_security_v1.types.server_tls_policy import GetServerTlsPolicyRequest -from google.cloud.network_security_v1.types.server_tls_policy import ListServerTlsPoliciesRequest -from google.cloud.network_security_v1.types.server_tls_policy import ListServerTlsPoliciesResponse -from google.cloud.network_security_v1.types.server_tls_policy import ServerTlsPolicy -from google.cloud.network_security_v1.types.server_tls_policy import UpdateServerTlsPolicyRequest -from google.cloud.network_security_v1.types.tls import CertificateProvider -from google.cloud.network_security_v1.types.tls import CertificateProviderInstance -from google.cloud.network_security_v1.types.tls import GrpcEndpoint -from google.cloud.network_security_v1.types.tls import ValidationCA - -__all__ = ('AddressGroupServiceClient', - 'AddressGroupServiceAsyncClient', - 'NetworkSecurityClient', - 'NetworkSecurityAsyncClient', - 'OrganizationAddressGroupServiceClient', - 'OrganizationAddressGroupServiceAsyncClient', - 'AddAddressGroupItemsRequest', - 'AddressGroup', - 'CloneAddressGroupItemsRequest', - 'CreateAddressGroupRequest', - 'DeleteAddressGroupRequest', - 'GetAddressGroupRequest', - 'ListAddressGroupReferencesRequest', - 'ListAddressGroupReferencesResponse', - 'ListAddressGroupsRequest', - 'ListAddressGroupsResponse', - 'RemoveAddressGroupItemsRequest', - 'UpdateAddressGroupRequest', - 'AuthorizationPolicy', - 'CreateAuthorizationPolicyRequest', - 'DeleteAuthorizationPolicyRequest', - 'GetAuthorizationPolicyRequest', - 'ListAuthorizationPoliciesRequest', - 'ListAuthorizationPoliciesResponse', - 'UpdateAuthorizationPolicyRequest', - 'ClientTlsPolicy', - 'CreateClientTlsPolicyRequest', - 'DeleteClientTlsPolicyRequest', - 'GetClientTlsPolicyRequest', - 'ListClientTlsPoliciesRequest', - 'ListClientTlsPoliciesResponse', - 'UpdateClientTlsPolicyRequest', - 'OperationMetadata', - 'CreateServerTlsPolicyRequest', - 'DeleteServerTlsPolicyRequest', - 'GetServerTlsPolicyRequest', - 'ListServerTlsPoliciesRequest', - 'ListServerTlsPoliciesResponse', - 'ServerTlsPolicy', - 'UpdateServerTlsPolicyRequest', - 'CertificateProvider', - 'CertificateProviderInstance', - 'GrpcEndpoint', - 'ValidationCA', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/py.typed b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/py.typed deleted file mode 100644 index 41b3c3019247..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/__init__.py deleted file mode 100644 index 64b6f78340a7..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/__init__.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.network_security_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.address_group_service import AddressGroupServiceClient -from .services.address_group_service import AddressGroupServiceAsyncClient -from .services.network_security import NetworkSecurityClient -from .services.network_security import NetworkSecurityAsyncClient -from .services.organization_address_group_service import OrganizationAddressGroupServiceClient -from .services.organization_address_group_service import OrganizationAddressGroupServiceAsyncClient - -from .types.address_group import AddAddressGroupItemsRequest -from .types.address_group import AddressGroup -from .types.address_group import CloneAddressGroupItemsRequest -from .types.address_group import CreateAddressGroupRequest -from .types.address_group import DeleteAddressGroupRequest -from .types.address_group import GetAddressGroupRequest -from .types.address_group import ListAddressGroupReferencesRequest -from .types.address_group import ListAddressGroupReferencesResponse -from .types.address_group import ListAddressGroupsRequest -from .types.address_group import ListAddressGroupsResponse -from .types.address_group import RemoveAddressGroupItemsRequest -from .types.address_group import UpdateAddressGroupRequest -from .types.authorization_policy import AuthorizationPolicy -from .types.authorization_policy import CreateAuthorizationPolicyRequest -from .types.authorization_policy import DeleteAuthorizationPolicyRequest -from .types.authorization_policy import GetAuthorizationPolicyRequest -from .types.authorization_policy import ListAuthorizationPoliciesRequest -from .types.authorization_policy import ListAuthorizationPoliciesResponse -from .types.authorization_policy import UpdateAuthorizationPolicyRequest -from .types.client_tls_policy import ClientTlsPolicy -from .types.client_tls_policy import CreateClientTlsPolicyRequest -from .types.client_tls_policy import DeleteClientTlsPolicyRequest -from .types.client_tls_policy import GetClientTlsPolicyRequest -from .types.client_tls_policy import ListClientTlsPoliciesRequest -from .types.client_tls_policy import ListClientTlsPoliciesResponse -from .types.client_tls_policy import UpdateClientTlsPolicyRequest -from .types.common import OperationMetadata -from .types.server_tls_policy import CreateServerTlsPolicyRequest -from .types.server_tls_policy import DeleteServerTlsPolicyRequest -from .types.server_tls_policy import GetServerTlsPolicyRequest -from .types.server_tls_policy import ListServerTlsPoliciesRequest -from .types.server_tls_policy import ListServerTlsPoliciesResponse -from .types.server_tls_policy import ServerTlsPolicy -from .types.server_tls_policy import UpdateServerTlsPolicyRequest -from .types.tls import CertificateProvider -from .types.tls import CertificateProviderInstance -from .types.tls import GrpcEndpoint -from .types.tls import ValidationCA - -__all__ = ( - 'AddressGroupServiceAsyncClient', - 'NetworkSecurityAsyncClient', - 'OrganizationAddressGroupServiceAsyncClient', -'AddAddressGroupItemsRequest', -'AddressGroup', -'AddressGroupServiceClient', -'AuthorizationPolicy', -'CertificateProvider', -'CertificateProviderInstance', -'ClientTlsPolicy', -'CloneAddressGroupItemsRequest', -'CreateAddressGroupRequest', -'CreateAuthorizationPolicyRequest', -'CreateClientTlsPolicyRequest', -'CreateServerTlsPolicyRequest', -'DeleteAddressGroupRequest', -'DeleteAuthorizationPolicyRequest', -'DeleteClientTlsPolicyRequest', -'DeleteServerTlsPolicyRequest', -'GetAddressGroupRequest', -'GetAuthorizationPolicyRequest', -'GetClientTlsPolicyRequest', -'GetServerTlsPolicyRequest', -'GrpcEndpoint', -'ListAddressGroupReferencesRequest', -'ListAddressGroupReferencesResponse', -'ListAddressGroupsRequest', -'ListAddressGroupsResponse', -'ListAuthorizationPoliciesRequest', -'ListAuthorizationPoliciesResponse', -'ListClientTlsPoliciesRequest', -'ListClientTlsPoliciesResponse', -'ListServerTlsPoliciesRequest', -'ListServerTlsPoliciesResponse', -'NetworkSecurityClient', -'OperationMetadata', -'OrganizationAddressGroupServiceClient', -'RemoveAddressGroupItemsRequest', -'ServerTlsPolicy', -'UpdateAddressGroupRequest', -'UpdateAuthorizationPolicyRequest', -'UpdateClientTlsPolicyRequest', -'UpdateServerTlsPolicyRequest', -'ValidationCA', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_metadata.json deleted file mode 100644 index 7a369b0303ca..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_metadata.json +++ /dev/null @@ -1,561 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.network_security_v1", - "protoPackage": "google.cloud.networksecurity.v1", - "schema": "1.0", - "services": { - "AddressGroupService": { - "clients": { - "grpc": { - "libraryClient": "AddressGroupServiceClient", - "rpcs": { - "AddAddressGroupItems": { - "methods": [ - "add_address_group_items" - ] - }, - "CloneAddressGroupItems": { - "methods": [ - "clone_address_group_items" - ] - }, - "CreateAddressGroup": { - "methods": [ - "create_address_group" - ] - }, - "DeleteAddressGroup": { - "methods": [ - "delete_address_group" - ] - }, - "GetAddressGroup": { - "methods": [ - "get_address_group" - ] - }, - "ListAddressGroupReferences": { - "methods": [ - "list_address_group_references" - ] - }, - "ListAddressGroups": { - "methods": [ - "list_address_groups" - ] - }, - "RemoveAddressGroupItems": { - "methods": [ - "remove_address_group_items" - ] - }, - "UpdateAddressGroup": { - "methods": [ - "update_address_group" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AddressGroupServiceAsyncClient", - "rpcs": { - "AddAddressGroupItems": { - "methods": [ - "add_address_group_items" - ] - }, - "CloneAddressGroupItems": { - "methods": [ - "clone_address_group_items" - ] - }, - "CreateAddressGroup": { - "methods": [ - "create_address_group" - ] - }, - "DeleteAddressGroup": { - "methods": [ - "delete_address_group" - ] - }, - "GetAddressGroup": { - "methods": [ - "get_address_group" - ] - }, - "ListAddressGroupReferences": { - "methods": [ - "list_address_group_references" - ] - }, - "ListAddressGroups": { - "methods": [ - "list_address_groups" - ] - }, - "RemoveAddressGroupItems": { - "methods": [ - "remove_address_group_items" - ] - }, - "UpdateAddressGroup": { - "methods": [ - "update_address_group" - ] - } - } - }, - "rest": { - "libraryClient": "AddressGroupServiceClient", - "rpcs": { - "AddAddressGroupItems": { - "methods": [ - "add_address_group_items" - ] - }, - "CloneAddressGroupItems": { - "methods": [ - "clone_address_group_items" - ] - }, - "CreateAddressGroup": { - "methods": [ - "create_address_group" - ] - }, - "DeleteAddressGroup": { - "methods": [ - "delete_address_group" - ] - }, - "GetAddressGroup": { - "methods": [ - "get_address_group" - ] - }, - "ListAddressGroupReferences": { - "methods": [ - "list_address_group_references" - ] - }, - "ListAddressGroups": { - "methods": [ - "list_address_groups" - ] - }, - "RemoveAddressGroupItems": { - "methods": [ - "remove_address_group_items" - ] - }, - "UpdateAddressGroup": { - "methods": [ - "update_address_group" - ] - } - } - } - } - }, - "NetworkSecurity": { - "clients": { - "grpc": { - "libraryClient": "NetworkSecurityClient", - "rpcs": { - "CreateAuthorizationPolicy": { - "methods": [ - "create_authorization_policy" - ] - }, - "CreateClientTlsPolicy": { - "methods": [ - "create_client_tls_policy" - ] - }, - "CreateServerTlsPolicy": { - "methods": [ - "create_server_tls_policy" - ] - }, - "DeleteAuthorizationPolicy": { - "methods": [ - "delete_authorization_policy" - ] - }, - "DeleteClientTlsPolicy": { - "methods": [ - "delete_client_tls_policy" - ] - }, - "DeleteServerTlsPolicy": { - "methods": [ - "delete_server_tls_policy" - ] - }, - "GetAuthorizationPolicy": { - "methods": [ - "get_authorization_policy" - ] - }, - "GetClientTlsPolicy": { - "methods": [ - "get_client_tls_policy" - ] - }, - "GetServerTlsPolicy": { - "methods": [ - "get_server_tls_policy" - ] - }, - "ListAuthorizationPolicies": { - "methods": [ - "list_authorization_policies" - ] - }, - "ListClientTlsPolicies": { - "methods": [ - "list_client_tls_policies" - ] - }, - "ListServerTlsPolicies": { - "methods": [ - "list_server_tls_policies" - ] - }, - "UpdateAuthorizationPolicy": { - "methods": [ - "update_authorization_policy" - ] - }, - "UpdateClientTlsPolicy": { - "methods": [ - "update_client_tls_policy" - ] - }, - "UpdateServerTlsPolicy": { - "methods": [ - "update_server_tls_policy" - ] - } - } - }, - "grpc-async": { - "libraryClient": "NetworkSecurityAsyncClient", - "rpcs": { - "CreateAuthorizationPolicy": { - "methods": [ - "create_authorization_policy" - ] - }, - "CreateClientTlsPolicy": { - "methods": [ - "create_client_tls_policy" - ] - }, - "CreateServerTlsPolicy": { - "methods": [ - "create_server_tls_policy" - ] - }, - "DeleteAuthorizationPolicy": { - "methods": [ - "delete_authorization_policy" - ] - }, - "DeleteClientTlsPolicy": { - "methods": [ - "delete_client_tls_policy" - ] - }, - "DeleteServerTlsPolicy": { - "methods": [ - "delete_server_tls_policy" - ] - }, - "GetAuthorizationPolicy": { - "methods": [ - "get_authorization_policy" - ] - }, - "GetClientTlsPolicy": { - "methods": [ - "get_client_tls_policy" - ] - }, - "GetServerTlsPolicy": { - "methods": [ - "get_server_tls_policy" - ] - }, - "ListAuthorizationPolicies": { - "methods": [ - "list_authorization_policies" - ] - }, - "ListClientTlsPolicies": { - "methods": [ - "list_client_tls_policies" - ] - }, - "ListServerTlsPolicies": { - "methods": [ - "list_server_tls_policies" - ] - }, - "UpdateAuthorizationPolicy": { - "methods": [ - "update_authorization_policy" - ] - }, - "UpdateClientTlsPolicy": { - "methods": [ - "update_client_tls_policy" - ] - }, - "UpdateServerTlsPolicy": { - "methods": [ - "update_server_tls_policy" - ] - } - } - }, - "rest": { - "libraryClient": "NetworkSecurityClient", - "rpcs": { - "CreateAuthorizationPolicy": { - "methods": [ - "create_authorization_policy" - ] - }, - "CreateClientTlsPolicy": { - "methods": [ - "create_client_tls_policy" - ] - }, - "CreateServerTlsPolicy": { - "methods": [ - "create_server_tls_policy" - ] - }, - "DeleteAuthorizationPolicy": { - "methods": [ - "delete_authorization_policy" - ] - }, - "DeleteClientTlsPolicy": { - "methods": [ - "delete_client_tls_policy" - ] - }, - "DeleteServerTlsPolicy": { - "methods": [ - "delete_server_tls_policy" - ] - }, - "GetAuthorizationPolicy": { - "methods": [ - "get_authorization_policy" - ] - }, - "GetClientTlsPolicy": { - "methods": [ - "get_client_tls_policy" - ] - }, - "GetServerTlsPolicy": { - "methods": [ - "get_server_tls_policy" - ] - }, - "ListAuthorizationPolicies": { - "methods": [ - "list_authorization_policies" - ] - }, - "ListClientTlsPolicies": { - "methods": [ - "list_client_tls_policies" - ] - }, - "ListServerTlsPolicies": { - "methods": [ - "list_server_tls_policies" - ] - }, - "UpdateAuthorizationPolicy": { - "methods": [ - "update_authorization_policy" - ] - }, - "UpdateClientTlsPolicy": { - "methods": [ - "update_client_tls_policy" - ] - }, - "UpdateServerTlsPolicy": { - "methods": [ - "update_server_tls_policy" - ] - } - } - } - } - }, - "OrganizationAddressGroupService": { - "clients": { - "grpc": { - "libraryClient": "OrganizationAddressGroupServiceClient", - "rpcs": { - "AddAddressGroupItems": { - "methods": [ - "add_address_group_items" - ] - }, - "CloneAddressGroupItems": { - "methods": [ - "clone_address_group_items" - ] - }, - "CreateAddressGroup": { - "methods": [ - "create_address_group" - ] - }, - "DeleteAddressGroup": { - "methods": [ - "delete_address_group" - ] - }, - "GetAddressGroup": { - "methods": [ - "get_address_group" - ] - }, - "ListAddressGroupReferences": { - "methods": [ - "list_address_group_references" - ] - }, - "ListAddressGroups": { - "methods": [ - "list_address_groups" - ] - }, - "RemoveAddressGroupItems": { - "methods": [ - "remove_address_group_items" - ] - }, - "UpdateAddressGroup": { - "methods": [ - "update_address_group" - ] - } - } - }, - "grpc-async": { - "libraryClient": "OrganizationAddressGroupServiceAsyncClient", - "rpcs": { - "AddAddressGroupItems": { - "methods": [ - "add_address_group_items" - ] - }, - "CloneAddressGroupItems": { - "methods": [ - "clone_address_group_items" - ] - }, - "CreateAddressGroup": { - "methods": [ - "create_address_group" - ] - }, - "DeleteAddressGroup": { - "methods": [ - "delete_address_group" - ] - }, - "GetAddressGroup": { - "methods": [ - "get_address_group" - ] - }, - "ListAddressGroupReferences": { - "methods": [ - "list_address_group_references" - ] - }, - "ListAddressGroups": { - "methods": [ - "list_address_groups" - ] - }, - "RemoveAddressGroupItems": { - "methods": [ - "remove_address_group_items" - ] - }, - "UpdateAddressGroup": { - "methods": [ - "update_address_group" - ] - } - } - }, - "rest": { - "libraryClient": "OrganizationAddressGroupServiceClient", - "rpcs": { - "AddAddressGroupItems": { - "methods": [ - "add_address_group_items" - ] - }, - "CloneAddressGroupItems": { - "methods": [ - "clone_address_group_items" - ] - }, - "CreateAddressGroup": { - "methods": [ - "create_address_group" - ] - }, - "DeleteAddressGroup": { - "methods": [ - "delete_address_group" - ] - }, - "GetAddressGroup": { - "methods": [ - "get_address_group" - ] - }, - "ListAddressGroupReferences": { - "methods": [ - "list_address_group_references" - ] - }, - "ListAddressGroups": { - "methods": [ - "list_address_groups" - ] - }, - "RemoveAddressGroupItems": { - "methods": [ - "remove_address_group_items" - ] - }, - "UpdateAddressGroup": { - "methods": [ - "update_address_group" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/py.typed b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/py.typed deleted file mode 100644 index 41b3c3019247..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/__init__.py deleted file mode 100644 index cbf94b283c70..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/__init__.py deleted file mode 100644 index cddb3cfba9e6..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 NetworkSecurityClient -from .async_client import NetworkSecurityAsyncClient - -__all__ = ( - 'NetworkSecurityClient', - 'NetworkSecurityAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/async_client.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/async_client.py deleted file mode 100644 index ee7c91c0d573..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/async_client.py +++ /dev/null @@ -1,2866 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.network_security_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.services.network_security import pagers -from google.cloud.network_security_v1.types import authorization_policy -from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1.types import client_tls_policy -from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1.types import common -from google.cloud.network_security_v1.types import server_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy -from google.cloud.network_security_v1.types import tls -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport -from .client import NetworkSecurityClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class NetworkSecurityAsyncClient: - """Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - """ - - _client: NetworkSecurityClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = NetworkSecurityClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = NetworkSecurityClient._DEFAULT_UNIVERSE - - authorization_policy_path = staticmethod(NetworkSecurityClient.authorization_policy_path) - parse_authorization_policy_path = staticmethod(NetworkSecurityClient.parse_authorization_policy_path) - client_tls_policy_path = staticmethod(NetworkSecurityClient.client_tls_policy_path) - parse_client_tls_policy_path = staticmethod(NetworkSecurityClient.parse_client_tls_policy_path) - server_tls_policy_path = staticmethod(NetworkSecurityClient.server_tls_policy_path) - parse_server_tls_policy_path = staticmethod(NetworkSecurityClient.parse_server_tls_policy_path) - common_billing_account_path = staticmethod(NetworkSecurityClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(NetworkSecurityClient.parse_common_billing_account_path) - common_folder_path = staticmethod(NetworkSecurityClient.common_folder_path) - parse_common_folder_path = staticmethod(NetworkSecurityClient.parse_common_folder_path) - common_organization_path = staticmethod(NetworkSecurityClient.common_organization_path) - parse_common_organization_path = staticmethod(NetworkSecurityClient.parse_common_organization_path) - common_project_path = staticmethod(NetworkSecurityClient.common_project_path) - parse_common_project_path = staticmethod(NetworkSecurityClient.parse_common_project_path) - common_location_path = staticmethod(NetworkSecurityClient.common_location_path) - parse_common_location_path = staticmethod(NetworkSecurityClient.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: - NetworkSecurityAsyncClient: The constructed client. - """ - return NetworkSecurityClient.from_service_account_info.__func__(NetworkSecurityAsyncClient, 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: - NetworkSecurityAsyncClient: The constructed client. - """ - return NetworkSecurityClient.from_service_account_file.__func__(NetworkSecurityAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return NetworkSecurityClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> NetworkSecurityTransport: - """Returns the transport used by the client instance. - - Returns: - NetworkSecurityTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = NetworkSecurityClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the network security async 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the NetworkSecurityTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client = NetworkSecurityClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.networksecurity_v1.NetworkSecurityAsyncClient`.", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "credentialsType": None, - } - ) - - async def list_authorization_policies(self, - request: Optional[Union[authorization_policy.ListAuthorizationPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAuthorizationPoliciesAsyncPager: - r"""Lists AuthorizationPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_list_authorization_policies(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.ListAuthorizationPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_authorization_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest, dict]]): - The request object. Request used with the - ListAuthorizationPolicies method. - parent (:class:`str`): - Required. The project and location from which the - AuthorizationPolicies should be listed, specified in the - format ``projects/{project}/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager: - Response returned by the - ListAuthorizationPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.ListAuthorizationPoliciesRequest): - request = authorization_policy.ListAuthorizationPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_authorization_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.ListAuthorizationPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_authorization_policy(self, - request: Optional[Union[authorization_policy.GetAuthorizationPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> authorization_policy.AuthorizationPolicy: - r"""Gets details of a single AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_get_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.GetAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_authorization_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest, dict]]): - The request object. Request used by the - GetAuthorizationPolicy method. - name (:class:`str`): - Required. A name of the AuthorizationPolicy to get. Must - be in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.types.AuthorizationPolicy: - AuthorizationPolicy is a resource - that specifies how a server should - authorize incoming connections. This - resource in itself does not change the - configuration unless it's attached to a - target https proxy or endpoint config - selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.GetAuthorizationPolicyRequest): - request = authorization_policy.GetAuthorizationPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_authorization_policy(self, - request: Optional[Union[gcn_authorization_policy.CreateAuthorizationPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, - authorization_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new AuthorizationPolicy in a given project - and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_create_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1.CreateAuthorizationPolicyRequest( - parent="parent_value", - authorization_policy_id="authorization_policy_id_value", - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.create_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest, dict]]): - The request object. Request used by the - CreateAuthorizationPolicy method. - parent (:class:`str`): - Required. The parent resource of the - AuthorizationPolicy. Must be in the format - ``projects/{project}/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - authorization_policy (:class:`google.cloud.network_security_v1.types.AuthorizationPolicy`): - Required. AuthorizationPolicy - resource to be created. - - This corresponds to the ``authorization_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - authorization_policy_id (:class:`str`): - Required. Short name of the AuthorizationPolicy resource - to be created. This value should be 1-63 characters - long, containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "authz_policy". - - This corresponds to the ``authorization_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server - should authorize incoming connections. This resource - in itself does not change the configuration unless - it's attached to a target https proxy or endpoint - config selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, authorization_policy, authorization_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_authorization_policy.CreateAuthorizationPolicyRequest): - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if authorization_policy is not None: - request.authorization_policy = authorization_policy - if authorization_policy_id is not None: - request.authorization_policy_id = authorization_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_authorization_policy.AuthorizationPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_authorization_policy(self, - request: Optional[Union[gcn_authorization_policy.UpdateAuthorizationPolicyRequest, dict]] = None, - *, - authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single - AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_update_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1.UpdateAuthorizationPolicyRequest( - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.update_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest, dict]]): - The request object. Request used by the - UpdateAuthorizationPolicy method. - authorization_policy (:class:`google.cloud.network_security_v1.types.AuthorizationPolicy`): - Required. Updated AuthorizationPolicy - resource. - - This corresponds to the ``authorization_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Field mask is used to specify the fields to be - overwritten in the AuthorizationPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server - should authorize incoming connections. This resource - in itself does not change the configuration unless - it's attached to a target https proxy or endpoint - config selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [authorization_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_authorization_policy.UpdateAuthorizationPolicyRequest): - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if authorization_policy is not None: - request.authorization_policy = authorization_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_authorization_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("authorization_policy.name", request.authorization_policy.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_authorization_policy.AuthorizationPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_authorization_policy(self, - request: Optional[Union[authorization_policy.DeleteAuthorizationPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_delete_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest, dict]]): - The request object. Request used by the - DeleteAuthorizationPolicy method. - name (:class:`str`): - Required. A name of the AuthorizationPolicy to delete. - Must be in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.DeleteAuthorizationPolicyRequest): - request = authorization_policy.DeleteAuthorizationPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_server_tls_policies(self, - request: Optional[Union[server_tls_policy.ListServerTlsPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListServerTlsPoliciesAsyncPager: - r"""Lists ServerTlsPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_list_server_tls_policies(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.ListServerTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_server_tls_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest, dict]]): - The request object. Request used by the - ListServerTlsPolicies method. - parent (:class:`str`): - Required. The project and location from which the - ServerTlsPolicies should be listed, specified in the - format ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager: - Response returned by the - ListServerTlsPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.ListServerTlsPoliciesRequest): - request = server_tls_policy.ListServerTlsPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_server_tls_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.ListServerTlsPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_server_tls_policy(self, - request: Optional[Union[server_tls_policy.GetServerTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> server_tls_policy.ServerTlsPolicy: - r"""Gets details of a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_get_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.GetServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_server_tls_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.GetServerTlsPolicyRequest, dict]]): - The request object. Request used by the - GetServerTlsPolicy method. - name (:class:`str`): - Required. A name of the ServerTlsPolicy to get. Must be - in the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.types.ServerTlsPolicy: - ServerTlsPolicy is a resource that - specifies how a server should - authenticate incoming requests. This - resource itself does not affect - configuration unless it is attached to a - target https proxy or endpoint config - selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.GetServerTlsPolicyRequest): - request = server_tls_policy.GetServerTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_server_tls_policy(self, - request: Optional[Union[gcn_server_tls_policy.CreateServerTlsPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, - server_tls_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new ServerTlsPolicy in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_create_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1.CreateServerTlsPolicyRequest( - parent="parent_value", - server_tls_policy_id="server_tls_policy_id_value", - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.create_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest, dict]]): - The request object. Request used by the - CreateServerTlsPolicy method. - parent (:class:`str`): - Required. The parent resource of the ServerTlsPolicy. - Must be in the format - ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - server_tls_policy (:class:`google.cloud.network_security_v1.types.ServerTlsPolicy`): - Required. ServerTlsPolicy resource to - be created. - - This corresponds to the ``server_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - server_tls_policy_id (:class:`str`): - Required. Short name of the ServerTlsPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "server_mtls_policy". - - This corresponds to the ``server_tls_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate - incoming requests. This resource itself does not - affect configuration unless it is attached to a - target https proxy or endpoint config selector - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, server_tls_policy, server_tls_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_server_tls_policy.CreateServerTlsPolicyRequest): - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if server_tls_policy is not None: - request.server_tls_policy = server_tls_policy - if server_tls_policy_id is not None: - request.server_tls_policy_id = server_tls_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_server_tls_policy.ServerTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_server_tls_policy(self, - request: Optional[Union[gcn_server_tls_policy.UpdateServerTlsPolicyRequest, dict]] = None, - *, - server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_update_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1.UpdateServerTlsPolicyRequest( - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.update_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest, dict]]): - The request object. Request used by UpdateServerTlsPolicy - method. - server_tls_policy (:class:`google.cloud.network_security_v1.types.ServerTlsPolicy`): - Required. Updated ServerTlsPolicy - resource. - - This corresponds to the ``server_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Field mask is used to specify the fields to be - overwritten in the ServerTlsPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate - incoming requests. This resource itself does not - affect configuration unless it is attached to a - target https proxy or endpoint config selector - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [server_tls_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_server_tls_policy.UpdateServerTlsPolicyRequest): - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if server_tls_policy is not None: - request.server_tls_policy = server_tls_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_server_tls_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("server_tls_policy.name", request.server_tls_policy.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_server_tls_policy.ServerTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_server_tls_policy(self, - request: Optional[Union[server_tls_policy.DeleteServerTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_delete_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest, dict]]): - The request object. Request used by the - DeleteServerTlsPolicy method. - name (:class:`str`): - Required. A name of the ServerTlsPolicy to delete. Must - be in the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.DeleteServerTlsPolicyRequest): - request = server_tls_policy.DeleteServerTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_client_tls_policies(self, - request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListClientTlsPoliciesAsyncPager: - r"""Lists ClientTlsPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest, dict]]): - The request object. Request used by the - ListClientTlsPolicies method. - parent (:class:`str`): - Required. The project and location from which the - ClientTlsPolicies should be listed, specified in the - format ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager: - Response returned by the - ListClientTlsPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): - request = client_tls_policy.ListClientTlsPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_client_tls_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.ListClientTlsPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_client_tls_policy(self, - request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> client_tls_policy.ClientTlsPolicy: - r"""Gets details of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.GetClientTlsPolicyRequest, dict]]): - The request object. Request used by the - GetClientTlsPolicy method. - name (:class:`str`): - Required. A name of the ClientTlsPolicy to get. Must be - in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.types.ClientTlsPolicy: - ClientTlsPolicy is a resource that - specifies how a client should - authenticate connections to backends of - a service. This resource itself does not - affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): - request = client_tls_policy.GetClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - client_tls_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new ClientTlsPolicy in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest, dict]]): - The request object. Request used by the - CreateClientTlsPolicy method. - parent (:class:`str`): - Required. The parent resource of the ClientTlsPolicy. - Must be in the format - ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy (:class:`google.cloud.network_security_v1.types.ClientTlsPolicy`): - Required. ClientTlsPolicy resource to - be created. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy_id (:class:`str`): - Required. Short name of the ClientTlsPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "client_mtls_policy". - - This corresponds to the ``client_tls_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, client_tls_policy, client_tls_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if client_tls_policy_id is not None: - request.client_tls_policy_id = client_tls_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, - *, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest, dict]]): - The request object. Request used by UpdateClientTlsPolicy - method. - client_tls_policy (:class:`google.cloud.network_security_v1.types.ClientTlsPolicy`): - Required. Updated ClientTlsPolicy - resource. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Field mask is used to specify the fields to be - overwritten in the ClientTlsPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [client_tls_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_client_tls_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("client_tls_policy.name", request.client_tls_policy.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_client_tls_policy(self, - request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - async def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest, dict]]): - The request object. Request used by the - DeleteClientTlsPolicy method. - name (:class:`str`): - Required. A name of the ClientTlsPolicy to delete. Must - be in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): - request = client_tls_policy.DeleteClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_operations] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_location] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_locations] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "NetworkSecurityAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -__all__ = ( - "NetworkSecurityAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/client.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/client.py deleted file mode 100644 index c07f553c447b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/client.py +++ /dev/null @@ -1,3253 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 http import HTTPStatus -import json -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.network_security_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.services.network_security import pagers -from google.cloud.network_security_v1.types import authorization_policy -from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1.types import client_tls_policy -from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1.types import common -from google.cloud.network_security_v1.types import server_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy -from google.cloud.network_security_v1.types import tls -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import NetworkSecurityGrpcTransport -from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport -from .transports.rest import NetworkSecurityRestTransport - - -class NetworkSecurityClientMeta(type): - """Metaclass for the NetworkSecurity 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[NetworkSecurityTransport]] - _transport_registry["grpc"] = NetworkSecurityGrpcTransport - _transport_registry["grpc_asyncio"] = NetworkSecurityGrpcAsyncIOTransport - _transport_registry["rest"] = NetworkSecurityRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[NetworkSecurityTransport]: - """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 NetworkSecurityClient(metaclass=NetworkSecurityClientMeta): - """Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - """ - - @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") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "networksecurity.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "networksecurity.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @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: - NetworkSecurityClient: 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: - NetworkSecurityClient: 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) -> NetworkSecurityTransport: - """Returns the transport used by the client instance. - - Returns: - NetworkSecurityTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def authorization_policy_path(project: str,location: str,authorization_policy: str,) -> str: - """Returns a fully-qualified authorization_policy string.""" - return "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format(project=project, location=location, authorization_policy=authorization_policy, ) - - @staticmethod - def parse_authorization_policy_path(path: str) -> Dict[str,str]: - """Parses a authorization_policy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/authorizationPolicies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def client_tls_policy_path(project: str,location: str,client_tls_policy: str,) -> str: - """Returns a fully-qualified client_tls_policy string.""" - return "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) - - @staticmethod - def parse_client_tls_policy_path(path: str) -> Dict[str,str]: - """Parses a client_tls_policy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clientTlsPolicies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def server_tls_policy_path(project: str,location: str,server_tls_policy: str,) -> str: - """Returns a fully-qualified server_tls_policy string.""" - return "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format(project=project, location=location, server_tls_policy=server_tls_policy, ) - - @staticmethod - def parse_server_tls_policy_path(path: str) -> Dict[str,str]: - """Parses a server_tls_policy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/serverTlsPolicies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = NetworkSecurityClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError - ) -> None: - """Adds credential info string to error details for 401/403/404 errors. - - Args: - error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. - """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the network security 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the NetworkSecurityTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = NetworkSecurityClient._read_environment_variables() - self._client_cert_source = NetworkSecurityClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = NetworkSecurityClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, NetworkSecurityTransport) - if transport_provided: - # transport is a NetworkSecurityTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(NetworkSecurityTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - NetworkSecurityClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[NetworkSecurityTransport], Callable[..., NetworkSecurityTransport]] = ( - NetworkSecurityClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., NetworkSecurityTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.networksecurity_v1.NetworkSecurityClient`.", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "credentialsType": None, - } - ) - - def list_authorization_policies(self, - request: Optional[Union[authorization_policy.ListAuthorizationPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAuthorizationPoliciesPager: - r"""Lists AuthorizationPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_list_authorization_policies(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.ListAuthorizationPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_authorization_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest, dict]): - The request object. Request used with the - ListAuthorizationPolicies method. - parent (str): - Required. The project and location from which the - AuthorizationPolicies should be listed, specified in the - format ``projects/{project}/locations/{location}``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesPager: - Response returned by the - ListAuthorizationPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.ListAuthorizationPoliciesRequest): - request = authorization_policy.ListAuthorizationPoliciesRequest(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_authorization_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.ListAuthorizationPoliciesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_authorization_policy(self, - request: Optional[Union[authorization_policy.GetAuthorizationPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> authorization_policy.AuthorizationPolicy: - r"""Gets details of a single AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_get_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.GetAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_authorization_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest, dict]): - The request object. Request used by the - GetAuthorizationPolicy method. - name (str): - Required. A name of the AuthorizationPolicy to get. Must - be in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.types.AuthorizationPolicy: - AuthorizationPolicy is a resource - that specifies how a server should - authorize incoming connections. This - resource in itself does not change the - configuration unless it's attached to a - target https proxy or endpoint config - selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.GetAuthorizationPolicyRequest): - request = authorization_policy.GetAuthorizationPolicyRequest(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_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_authorization_policy(self, - request: Optional[Union[gcn_authorization_policy.CreateAuthorizationPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, - authorization_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new AuthorizationPolicy in a given project - and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_create_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1.CreateAuthorizationPolicyRequest( - parent="parent_value", - authorization_policy_id="authorization_policy_id_value", - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.create_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest, dict]): - The request object. Request used by the - CreateAuthorizationPolicy method. - parent (str): - Required. The parent resource of the - AuthorizationPolicy. Must be in the format - ``projects/{project}/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - authorization_policy (google.cloud.network_security_v1.types.AuthorizationPolicy): - Required. AuthorizationPolicy - resource to be created. - - This corresponds to the ``authorization_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - authorization_policy_id (str): - Required. Short name of the AuthorizationPolicy resource - to be created. This value should be 1-63 characters - long, containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "authz_policy". - - This corresponds to the ``authorization_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server - should authorize incoming connections. This resource - in itself does not change the configuration unless - it's attached to a target https proxy or endpoint - config selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, authorization_policy, authorization_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_authorization_policy.CreateAuthorizationPolicyRequest): - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if authorization_policy is not None: - request.authorization_policy = authorization_policy - if authorization_policy_id is not None: - request.authorization_policy_id = authorization_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_authorization_policy.AuthorizationPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_authorization_policy(self, - request: Optional[Union[gcn_authorization_policy.UpdateAuthorizationPolicyRequest, dict]] = None, - *, - authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single - AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_update_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1.UpdateAuthorizationPolicyRequest( - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.update_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest, dict]): - The request object. Request used by the - UpdateAuthorizationPolicy method. - authorization_policy (google.cloud.network_security_v1.types.AuthorizationPolicy): - Required. Updated AuthorizationPolicy - resource. - - This corresponds to the ``authorization_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the AuthorizationPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server - should authorize incoming connections. This resource - in itself does not change the configuration unless - it's attached to a target https proxy or endpoint - config selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [authorization_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_authorization_policy.UpdateAuthorizationPolicyRequest): - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if authorization_policy is not None: - request.authorization_policy = authorization_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_authorization_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("authorization_policy.name", request.authorization_policy.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_authorization_policy.AuthorizationPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_authorization_policy(self, - request: Optional[Union[authorization_policy.DeleteAuthorizationPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a single AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_delete_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest, dict]): - The request object. Request used by the - DeleteAuthorizationPolicy method. - name (str): - Required. A name of the AuthorizationPolicy to delete. - Must be in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.DeleteAuthorizationPolicyRequest): - request = authorization_policy.DeleteAuthorizationPolicyRequest(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_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def list_server_tls_policies(self, - request: Optional[Union[server_tls_policy.ListServerTlsPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListServerTlsPoliciesPager: - r"""Lists ServerTlsPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_list_server_tls_policies(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.ListServerTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_server_tls_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest, dict]): - The request object. Request used by the - ListServerTlsPolicies method. - parent (str): - Required. The project and location from which the - ServerTlsPolicies should be listed, specified in the - format ``projects/*/locations/{location}``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesPager: - Response returned by the - ListServerTlsPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.ListServerTlsPoliciesRequest): - request = server_tls_policy.ListServerTlsPoliciesRequest(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_server_tls_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.ListServerTlsPoliciesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_server_tls_policy(self, - request: Optional[Union[server_tls_policy.GetServerTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> server_tls_policy.ServerTlsPolicy: - r"""Gets details of a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_get_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.GetServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_server_tls_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.GetServerTlsPolicyRequest, dict]): - The request object. Request used by the - GetServerTlsPolicy method. - name (str): - Required. A name of the ServerTlsPolicy to get. Must be - in the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.types.ServerTlsPolicy: - ServerTlsPolicy is a resource that - specifies how a server should - authenticate incoming requests. This - resource itself does not affect - configuration unless it is attached to a - target https proxy or endpoint config - selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.GetServerTlsPolicyRequest): - request = server_tls_policy.GetServerTlsPolicyRequest(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_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_server_tls_policy(self, - request: Optional[Union[gcn_server_tls_policy.CreateServerTlsPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, - server_tls_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new ServerTlsPolicy in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_create_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1.CreateServerTlsPolicyRequest( - parent="parent_value", - server_tls_policy_id="server_tls_policy_id_value", - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.create_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest, dict]): - The request object. Request used by the - CreateServerTlsPolicy method. - parent (str): - Required. The parent resource of the ServerTlsPolicy. - Must be in the format - ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - server_tls_policy (google.cloud.network_security_v1.types.ServerTlsPolicy): - Required. ServerTlsPolicy resource to - be created. - - This corresponds to the ``server_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - server_tls_policy_id (str): - Required. Short name of the ServerTlsPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "server_mtls_policy". - - This corresponds to the ``server_tls_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate - incoming requests. This resource itself does not - affect configuration unless it is attached to a - target https proxy or endpoint config selector - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, server_tls_policy, server_tls_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_server_tls_policy.CreateServerTlsPolicyRequest): - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if server_tls_policy is not None: - request.server_tls_policy = server_tls_policy - if server_tls_policy_id is not None: - request.server_tls_policy_id = server_tls_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_server_tls_policy.ServerTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_server_tls_policy(self, - request: Optional[Union[gcn_server_tls_policy.UpdateServerTlsPolicyRequest, dict]] = None, - *, - server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_update_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1.UpdateServerTlsPolicyRequest( - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.update_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest, dict]): - The request object. Request used by UpdateServerTlsPolicy - method. - server_tls_policy (google.cloud.network_security_v1.types.ServerTlsPolicy): - Required. Updated ServerTlsPolicy - resource. - - This corresponds to the ``server_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the ServerTlsPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate - incoming requests. This resource itself does not - affect configuration unless it is attached to a - target https proxy or endpoint config selector - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [server_tls_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_server_tls_policy.UpdateServerTlsPolicyRequest): - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if server_tls_policy is not None: - request.server_tls_policy = server_tls_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_server_tls_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("server_tls_policy.name", request.server_tls_policy.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_server_tls_policy.ServerTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_server_tls_policy(self, - request: Optional[Union[server_tls_policy.DeleteServerTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_delete_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest, dict]): - The request object. Request used by the - DeleteServerTlsPolicy method. - name (str): - Required. A name of the ServerTlsPolicy to delete. Must - be in the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.DeleteServerTlsPolicyRequest): - request = server_tls_policy.DeleteServerTlsPolicyRequest(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_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def list_client_tls_policies(self, - request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListClientTlsPoliciesPager: - r"""Lists ClientTlsPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest, dict]): - The request object. Request used by the - ListClientTlsPolicies method. - parent (str): - Required. The project and location from which the - ClientTlsPolicies should be listed, specified in the - format ``projects/*/locations/{location}``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesPager: - Response returned by the - ListClientTlsPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): - request = client_tls_policy.ListClientTlsPoliciesRequest(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_client_tls_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.ListClientTlsPoliciesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_client_tls_policy(self, - request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> client_tls_policy.ClientTlsPolicy: - r"""Gets details of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.GetClientTlsPolicyRequest, dict]): - The request object. Request used by the - GetClientTlsPolicy method. - name (str): - Required. A name of the ClientTlsPolicy to get. Must be - in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1.types.ClientTlsPolicy: - ClientTlsPolicy is a resource that - specifies how a client should - authenticate connections to backends of - a service. This resource itself does not - affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): - request = client_tls_policy.GetClientTlsPolicyRequest(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_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - client_tls_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new ClientTlsPolicy in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest, dict]): - The request object. Request used by the - CreateClientTlsPolicy method. - parent (str): - Required. The parent resource of the ClientTlsPolicy. - Must be in the format - ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy (google.cloud.network_security_v1.types.ClientTlsPolicy): - Required. ClientTlsPolicy resource to - be created. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy_id (str): - Required. Short name of the ClientTlsPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "client_mtls_policy". - - This corresponds to the ``client_tls_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, client_tls_policy, client_tls_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if client_tls_policy_id is not None: - request.client_tls_policy_id = client_tls_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, - *, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest, dict]): - The request object. Request used by UpdateClientTlsPolicy - method. - client_tls_policy (google.cloud.network_security_v1.types.ClientTlsPolicy): - Required. Updated ClientTlsPolicy - resource. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the ClientTlsPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [client_tls_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_client_tls_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("client_tls_policy.name", request.client_tls_policy.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_client_tls_policy(self, - request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1 - - def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest, dict]): - The request object. Request used by the - DeleteClientTlsPolicy method. - name (str): - Required. A name of the ClientTlsPolicy to delete. Must - be in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): - request = client_tls_policy.DeleteClientTlsPolicyRequest(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_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "NetworkSecurityClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_operations] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.cancel_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_location] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_locations] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - -__all__ = ( - "NetworkSecurityClient", -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/pagers.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/pagers.py deleted file mode 100644 index 1e2812463cc6..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/pagers.py +++ /dev/null @@ -1,446 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.cloud.network_security_v1.types import authorization_policy -from google.cloud.network_security_v1.types import client_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy - - -class ListAuthorizationPoliciesPager: - """A pager for iterating through ``list_authorization_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``authorization_policies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAuthorizationPolicies`` requests and continue to iterate - through the ``authorization_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse` - 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[..., authorization_policy.ListAuthorizationPoliciesResponse], - request: authorization_policy.ListAuthorizationPoliciesRequest, - response: authorization_policy.ListAuthorizationPoliciesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = authorization_policy.ListAuthorizationPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[authorization_policy.ListAuthorizationPoliciesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[authorization_policy.AuthorizationPolicy]: - for page in self.pages: - yield from page.authorization_policies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAuthorizationPoliciesAsyncPager: - """A pager for iterating through ``list_authorization_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``authorization_policies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAuthorizationPolicies`` requests and continue to iterate - through the ``authorization_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse` - 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[authorization_policy.ListAuthorizationPoliciesResponse]], - request: authorization_policy.ListAuthorizationPoliciesRequest, - response: authorization_policy.ListAuthorizationPoliciesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1.types.ListAuthorizationPoliciesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = authorization_policy.ListAuthorizationPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[authorization_policy.ListAuthorizationPoliciesResponse]: - 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[authorization_policy.AuthorizationPolicy]: - async def async_generator(): - async for page in self.pages: - for response in page.authorization_policies: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServerTlsPoliciesPager: - """A pager for iterating through ``list_server_tls_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``server_tls_policies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServerTlsPolicies`` requests and continue to iterate - through the ``server_tls_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse` - 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[..., server_tls_policy.ListServerTlsPoliciesResponse], - request: server_tls_policy.ListServerTlsPoliciesRequest, - response: server_tls_policy.ListServerTlsPoliciesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = server_tls_policy.ListServerTlsPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[server_tls_policy.ListServerTlsPoliciesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[server_tls_policy.ServerTlsPolicy]: - for page in self.pages: - yield from page.server_tls_policies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServerTlsPoliciesAsyncPager: - """A pager for iterating through ``list_server_tls_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``server_tls_policies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServerTlsPolicies`` requests and continue to iterate - through the ``server_tls_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse` - 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[server_tls_policy.ListServerTlsPoliciesResponse]], - request: server_tls_policy.ListServerTlsPoliciesRequest, - response: server_tls_policy.ListServerTlsPoliciesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1.types.ListServerTlsPoliciesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = server_tls_policy.ListServerTlsPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[server_tls_policy.ListServerTlsPoliciesResponse]: - 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[server_tls_policy.ServerTlsPolicy]: - async def async_generator(): - async for page in self.pages: - for response in page.server_tls_policies: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListClientTlsPoliciesPager: - """A pager for iterating through ``list_client_tls_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``client_tls_policies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListClientTlsPolicies`` requests and continue to iterate - through the ``client_tls_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse` - 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[..., client_tls_policy.ListClientTlsPoliciesResponse], - request: client_tls_policy.ListClientTlsPoliciesRequest, - response: client_tls_policy.ListClientTlsPoliciesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[client_tls_policy.ListClientTlsPoliciesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[client_tls_policy.ClientTlsPolicy]: - for page in self.pages: - yield from page.client_tls_policies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListClientTlsPoliciesAsyncPager: - """A pager for iterating through ``list_client_tls_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``client_tls_policies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListClientTlsPolicies`` requests and continue to iterate - through the ``client_tls_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse` - 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[client_tls_policy.ListClientTlsPoliciesResponse]], - request: client_tls_policy.ListClientTlsPoliciesRequest, - response: client_tls_policy.ListClientTlsPoliciesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1.types.ListClientTlsPoliciesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[client_tls_policy.ListClientTlsPoliciesResponse]: - 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[client_tls_policy.ClientTlsPolicy]: - async def async_generator(): - async for page in self.pages: - for response in page.client_tls_policies: - 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/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/README.rst b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/README.rst deleted file mode 100644 index e226a3cdbadb..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`NetworkSecurityTransport` is the ABC for all transports. -- public child `NetworkSecurityGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `NetworkSecurityGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseNetworkSecurityRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `NetworkSecurityRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/__init__.py deleted file mode 100644 index 6ee9817a2d9e..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 NetworkSecurityTransport -from .grpc import NetworkSecurityGrpcTransport -from .grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport -from .rest import NetworkSecurityRestTransport -from .rest import NetworkSecurityRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[NetworkSecurityTransport]] -_transport_registry['grpc'] = NetworkSecurityGrpcTransport -_transport_registry['grpc_asyncio'] = NetworkSecurityGrpcAsyncIOTransport -_transport_registry['rest'] = NetworkSecurityRestTransport - -__all__ = ( - 'NetworkSecurityTransport', - 'NetworkSecurityGrpcTransport', - 'NetworkSecurityGrpcAsyncIOTransport', - 'NetworkSecurityRestTransport', - 'NetworkSecurityRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/base.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/base.py deleted file mode 100644 index b08d873ced14..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/base.py +++ /dev/null @@ -1,497 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.network_security_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.types import authorization_policy -from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1.types import client_tls_policy -from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class NetworkSecurityTransport(abc.ABC): - """Abstract transport class for NetworkSecurity.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'networksecurity.googleapis.com' - - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # 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 and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_authorization_policies: gapic_v1.method.wrap_method( - self.list_authorization_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_authorization_policy: gapic_v1.method.wrap_method( - self.get_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_authorization_policy: gapic_v1.method.wrap_method( - self.create_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_authorization_policy: gapic_v1.method.wrap_method( - self.update_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_authorization_policy: gapic_v1.method.wrap_method( - self.delete_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_server_tls_policies: gapic_v1.method.wrap_method( - self.list_server_tls_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_server_tls_policy: gapic_v1.method.wrap_method( - self.get_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_server_tls_policy: gapic_v1.method.wrap_method( - self.create_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_server_tls_policy: gapic_v1.method.wrap_method( - self.update_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_server_tls_policy: gapic_v1.method.wrap_method( - self.delete_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_client_tls_policies: gapic_v1.method.wrap_method( - self.list_client_tls_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_client_tls_policy: gapic_v1.method.wrap_method( - self.get_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_client_tls_policy: gapic_v1.method.wrap_method( - self.create_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_client_tls_policy: gapic_v1.method.wrap_method( - self.update_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_client_tls_policy: gapic_v1.method.wrap_method( - self.delete_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_authorization_policies(self) -> Callable[ - [authorization_policy.ListAuthorizationPoliciesRequest], - Union[ - authorization_policy.ListAuthorizationPoliciesResponse, - Awaitable[authorization_policy.ListAuthorizationPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def get_authorization_policy(self) -> Callable[ - [authorization_policy.GetAuthorizationPolicyRequest], - Union[ - authorization_policy.AuthorizationPolicy, - Awaitable[authorization_policy.AuthorizationPolicy] - ]]: - raise NotImplementedError() - - @property - def create_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.CreateAuthorizationPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_authorization_policy(self) -> Callable[ - [authorization_policy.DeleteAuthorizationPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_server_tls_policies(self) -> Callable[ - [server_tls_policy.ListServerTlsPoliciesRequest], - Union[ - server_tls_policy.ListServerTlsPoliciesResponse, - Awaitable[server_tls_policy.ListServerTlsPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def get_server_tls_policy(self) -> Callable[ - [server_tls_policy.GetServerTlsPolicyRequest], - Union[ - server_tls_policy.ServerTlsPolicy, - Awaitable[server_tls_policy.ServerTlsPolicy] - ]]: - raise NotImplementedError() - - @property - def create_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.CreateServerTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_server_tls_policy(self) -> Callable[ - [server_tls_policy.DeleteServerTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - Union[ - client_tls_policy.ListClientTlsPoliciesResponse, - Awaitable[client_tls_policy.ListClientTlsPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - Union[ - client_tls_policy.ClientTlsPolicy, - Awaitable[client_tls_policy.ClientTlsPolicy] - ]]: - raise NotImplementedError() - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'NetworkSecurityTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc.py deleted file mode 100644 index 9a59b60498df..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc.py +++ /dev/null @@ -1,933 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 json -import logging as std_logging -import pickle -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.types import authorization_policy -from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1.types import client_tls_policy -from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class NetworkSecurityGrpcTransport(NetworkSecurityTransport): - """gRPC backend transport for NetworkSecurity. - - Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - - 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_authorization_policies(self) -> Callable[ - [authorization_policy.ListAuthorizationPoliciesRequest], - authorization_policy.ListAuthorizationPoliciesResponse]: - r"""Return a callable for the list authorization policies method over gRPC. - - Lists AuthorizationPolicies in a given project and - location. - - Returns: - Callable[[~.ListAuthorizationPoliciesRequest], - ~.ListAuthorizationPoliciesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_authorization_policies' not in self._stubs: - self._stubs['list_authorization_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/ListAuthorizationPolicies', - request_serializer=authorization_policy.ListAuthorizationPoliciesRequest.serialize, - response_deserializer=authorization_policy.ListAuthorizationPoliciesResponse.deserialize, - ) - return self._stubs['list_authorization_policies'] - - @property - def get_authorization_policy(self) -> Callable[ - [authorization_policy.GetAuthorizationPolicyRequest], - authorization_policy.AuthorizationPolicy]: - r"""Return a callable for the get authorization policy method over gRPC. - - Gets details of a single AuthorizationPolicy. - - Returns: - Callable[[~.GetAuthorizationPolicyRequest], - ~.AuthorizationPolicy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_authorization_policy' not in self._stubs: - self._stubs['get_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/GetAuthorizationPolicy', - request_serializer=authorization_policy.GetAuthorizationPolicyRequest.serialize, - response_deserializer=authorization_policy.AuthorizationPolicy.deserialize, - ) - return self._stubs['get_authorization_policy'] - - @property - def create_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.CreateAuthorizationPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the create authorization policy method over gRPC. - - Creates a new AuthorizationPolicy in a given project - and location. - - Returns: - Callable[[~.CreateAuthorizationPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_authorization_policy' not in self._stubs: - self._stubs['create_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/CreateAuthorizationPolicy', - request_serializer=gcn_authorization_policy.CreateAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_authorization_policy'] - - @property - def update_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the update authorization policy method over gRPC. - - Updates the parameters of a single - AuthorizationPolicy. - - Returns: - Callable[[~.UpdateAuthorizationPolicyRequest], - ~.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 'update_authorization_policy' not in self._stubs: - self._stubs['update_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateAuthorizationPolicy', - request_serializer=gcn_authorization_policy.UpdateAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_authorization_policy'] - - @property - def delete_authorization_policy(self) -> Callable[ - [authorization_policy.DeleteAuthorizationPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete authorization policy method over gRPC. - - Deletes a single AuthorizationPolicy. - - Returns: - Callable[[~.DeleteAuthorizationPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_authorization_policy' not in self._stubs: - self._stubs['delete_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteAuthorizationPolicy', - request_serializer=authorization_policy.DeleteAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_authorization_policy'] - - @property - def list_server_tls_policies(self) -> Callable[ - [server_tls_policy.ListServerTlsPoliciesRequest], - server_tls_policy.ListServerTlsPoliciesResponse]: - r"""Return a callable for the list server tls policies method over gRPC. - - Lists ServerTlsPolicies in a given project and - location. - - Returns: - Callable[[~.ListServerTlsPoliciesRequest], - ~.ListServerTlsPoliciesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_server_tls_policies' not in self._stubs: - self._stubs['list_server_tls_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/ListServerTlsPolicies', - request_serializer=server_tls_policy.ListServerTlsPoliciesRequest.serialize, - response_deserializer=server_tls_policy.ListServerTlsPoliciesResponse.deserialize, - ) - return self._stubs['list_server_tls_policies'] - - @property - def get_server_tls_policy(self) -> Callable[ - [server_tls_policy.GetServerTlsPolicyRequest], - server_tls_policy.ServerTlsPolicy]: - r"""Return a callable for the get server tls policy method over gRPC. - - Gets details of a single ServerTlsPolicy. - - Returns: - Callable[[~.GetServerTlsPolicyRequest], - ~.ServerTlsPolicy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_server_tls_policy' not in self._stubs: - self._stubs['get_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/GetServerTlsPolicy', - request_serializer=server_tls_policy.GetServerTlsPolicyRequest.serialize, - response_deserializer=server_tls_policy.ServerTlsPolicy.deserialize, - ) - return self._stubs['get_server_tls_policy'] - - @property - def create_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.CreateServerTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the create server tls policy method over gRPC. - - Creates a new ServerTlsPolicy in a given project and - location. - - Returns: - Callable[[~.CreateServerTlsPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_server_tls_policy' not in self._stubs: - self._stubs['create_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/CreateServerTlsPolicy', - request_serializer=gcn_server_tls_policy.CreateServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_server_tls_policy'] - - @property - def update_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the update server tls policy method over gRPC. - - Updates the parameters of a single ServerTlsPolicy. - - Returns: - Callable[[~.UpdateServerTlsPolicyRequest], - ~.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 'update_server_tls_policy' not in self._stubs: - self._stubs['update_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateServerTlsPolicy', - request_serializer=gcn_server_tls_policy.UpdateServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_server_tls_policy'] - - @property - def delete_server_tls_policy(self) -> Callable[ - [server_tls_policy.DeleteServerTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete server tls policy method over gRPC. - - Deletes a single ServerTlsPolicy. - - Returns: - Callable[[~.DeleteServerTlsPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_server_tls_policy' not in self._stubs: - self._stubs['delete_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteServerTlsPolicy', - request_serializer=server_tls_policy.DeleteServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_server_tls_policy'] - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - client_tls_policy.ListClientTlsPoliciesResponse]: - r"""Return a callable for the list client tls policies method over gRPC. - - Lists ClientTlsPolicies in a given project and - location. - - Returns: - Callable[[~.ListClientTlsPoliciesRequest], - ~.ListClientTlsPoliciesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: - self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/ListClientTlsPolicies', - request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, - response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, - ) - return self._stubs['list_client_tls_policies'] - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - client_tls_policy.ClientTlsPolicy]: - r"""Return a callable for the get client tls policy method over gRPC. - - Gets details of a single ClientTlsPolicy. - - Returns: - Callable[[~.GetClientTlsPolicyRequest], - ~.ClientTlsPolicy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: - self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/GetClientTlsPolicy', - request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, - response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, - ) - return self._stubs['get_client_tls_policy'] - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the create client tls policy method over gRPC. - - Creates a new ClientTlsPolicy in a given project and - location. - - Returns: - Callable[[~.CreateClientTlsPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_client_tls_policy' not in self._stubs: - self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/CreateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_client_tls_policy'] - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the update client tls policy method over gRPC. - - Updates the parameters of a single ClientTlsPolicy. - - Returns: - Callable[[~.UpdateClientTlsPolicyRequest], - ~.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 'update_client_tls_policy' not in self._stubs: - self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_client_tls_policy'] - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete client tls policy method over gRPC. - - Deletes a single ClientTlsPolicy. - - Returns: - Callable[[~.DeleteClientTlsPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_client_tls_policy' not in self._stubs: - self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteClientTlsPolicy', - request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_client_tls_policy'] - - def close(self): - self._logged_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'NetworkSecurityGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc_asyncio.py deleted file mode 100644 index ddd1655d399a..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/grpc_asyncio.py +++ /dev/null @@ -1,1069 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 inspect -import json -import pickle -import logging as std_logging -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.types import authorization_policy -from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1.types import client_tls_policy -from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO -from .grpc import NetworkSecurityGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class NetworkSecurityGrpcAsyncIOTransport(NetworkSecurityTransport): - """gRPC AsyncIO backend transport for NetworkSecurity. - - Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - - 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_authorization_policies(self) -> Callable[ - [authorization_policy.ListAuthorizationPoliciesRequest], - Awaitable[authorization_policy.ListAuthorizationPoliciesResponse]]: - r"""Return a callable for the list authorization policies method over gRPC. - - Lists AuthorizationPolicies in a given project and - location. - - Returns: - Callable[[~.ListAuthorizationPoliciesRequest], - Awaitable[~.ListAuthorizationPoliciesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_authorization_policies' not in self._stubs: - self._stubs['list_authorization_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/ListAuthorizationPolicies', - request_serializer=authorization_policy.ListAuthorizationPoliciesRequest.serialize, - response_deserializer=authorization_policy.ListAuthorizationPoliciesResponse.deserialize, - ) - return self._stubs['list_authorization_policies'] - - @property - def get_authorization_policy(self) -> Callable[ - [authorization_policy.GetAuthorizationPolicyRequest], - Awaitable[authorization_policy.AuthorizationPolicy]]: - r"""Return a callable for the get authorization policy method over gRPC. - - Gets details of a single AuthorizationPolicy. - - Returns: - Callable[[~.GetAuthorizationPolicyRequest], - Awaitable[~.AuthorizationPolicy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_authorization_policy' not in self._stubs: - self._stubs['get_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/GetAuthorizationPolicy', - request_serializer=authorization_policy.GetAuthorizationPolicyRequest.serialize, - response_deserializer=authorization_policy.AuthorizationPolicy.deserialize, - ) - return self._stubs['get_authorization_policy'] - - @property - def create_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.CreateAuthorizationPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create authorization policy method over gRPC. - - Creates a new AuthorizationPolicy in a given project - and location. - - Returns: - Callable[[~.CreateAuthorizationPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_authorization_policy' not in self._stubs: - self._stubs['create_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/CreateAuthorizationPolicy', - request_serializer=gcn_authorization_policy.CreateAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_authorization_policy'] - - @property - def update_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update authorization policy method over gRPC. - - Updates the parameters of a single - AuthorizationPolicy. - - Returns: - Callable[[~.UpdateAuthorizationPolicyRequest], - 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 'update_authorization_policy' not in self._stubs: - self._stubs['update_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateAuthorizationPolicy', - request_serializer=gcn_authorization_policy.UpdateAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_authorization_policy'] - - @property - def delete_authorization_policy(self) -> Callable[ - [authorization_policy.DeleteAuthorizationPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete authorization policy method over gRPC. - - Deletes a single AuthorizationPolicy. - - Returns: - Callable[[~.DeleteAuthorizationPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_authorization_policy' not in self._stubs: - self._stubs['delete_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteAuthorizationPolicy', - request_serializer=authorization_policy.DeleteAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_authorization_policy'] - - @property - def list_server_tls_policies(self) -> Callable[ - [server_tls_policy.ListServerTlsPoliciesRequest], - Awaitable[server_tls_policy.ListServerTlsPoliciesResponse]]: - r"""Return a callable for the list server tls policies method over gRPC. - - Lists ServerTlsPolicies in a given project and - location. - - Returns: - Callable[[~.ListServerTlsPoliciesRequest], - Awaitable[~.ListServerTlsPoliciesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_server_tls_policies' not in self._stubs: - self._stubs['list_server_tls_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/ListServerTlsPolicies', - request_serializer=server_tls_policy.ListServerTlsPoliciesRequest.serialize, - response_deserializer=server_tls_policy.ListServerTlsPoliciesResponse.deserialize, - ) - return self._stubs['list_server_tls_policies'] - - @property - def get_server_tls_policy(self) -> Callable[ - [server_tls_policy.GetServerTlsPolicyRequest], - Awaitable[server_tls_policy.ServerTlsPolicy]]: - r"""Return a callable for the get server tls policy method over gRPC. - - Gets details of a single ServerTlsPolicy. - - Returns: - Callable[[~.GetServerTlsPolicyRequest], - Awaitable[~.ServerTlsPolicy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_server_tls_policy' not in self._stubs: - self._stubs['get_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/GetServerTlsPolicy', - request_serializer=server_tls_policy.GetServerTlsPolicyRequest.serialize, - response_deserializer=server_tls_policy.ServerTlsPolicy.deserialize, - ) - return self._stubs['get_server_tls_policy'] - - @property - def create_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.CreateServerTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create server tls policy method over gRPC. - - Creates a new ServerTlsPolicy in a given project and - location. - - Returns: - Callable[[~.CreateServerTlsPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_server_tls_policy' not in self._stubs: - self._stubs['create_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/CreateServerTlsPolicy', - request_serializer=gcn_server_tls_policy.CreateServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_server_tls_policy'] - - @property - def update_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update server tls policy method over gRPC. - - Updates the parameters of a single ServerTlsPolicy. - - Returns: - Callable[[~.UpdateServerTlsPolicyRequest], - 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 'update_server_tls_policy' not in self._stubs: - self._stubs['update_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateServerTlsPolicy', - request_serializer=gcn_server_tls_policy.UpdateServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_server_tls_policy'] - - @property - def delete_server_tls_policy(self) -> Callable[ - [server_tls_policy.DeleteServerTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete server tls policy method over gRPC. - - Deletes a single ServerTlsPolicy. - - Returns: - Callable[[~.DeleteServerTlsPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_server_tls_policy' not in self._stubs: - self._stubs['delete_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteServerTlsPolicy', - request_serializer=server_tls_policy.DeleteServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_server_tls_policy'] - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - Awaitable[client_tls_policy.ListClientTlsPoliciesResponse]]: - r"""Return a callable for the list client tls policies method over gRPC. - - Lists ClientTlsPolicies in a given project and - location. - - Returns: - Callable[[~.ListClientTlsPoliciesRequest], - Awaitable[~.ListClientTlsPoliciesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: - self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/ListClientTlsPolicies', - request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, - response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, - ) - return self._stubs['list_client_tls_policies'] - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - Awaitable[client_tls_policy.ClientTlsPolicy]]: - r"""Return a callable for the get client tls policy method over gRPC. - - Gets details of a single ClientTlsPolicy. - - Returns: - Callable[[~.GetClientTlsPolicyRequest], - Awaitable[~.ClientTlsPolicy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: - self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/GetClientTlsPolicy', - request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, - response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, - ) - return self._stubs['get_client_tls_policy'] - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create client tls policy method over gRPC. - - Creates a new ClientTlsPolicy in a given project and - location. - - Returns: - Callable[[~.CreateClientTlsPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_client_tls_policy' not in self._stubs: - self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/CreateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_client_tls_policy'] - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update client tls policy method over gRPC. - - Updates the parameters of a single ClientTlsPolicy. - - Returns: - Callable[[~.UpdateClientTlsPolicyRequest], - 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 'update_client_tls_policy' not in self._stubs: - self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/UpdateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_client_tls_policy'] - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete client tls policy method over gRPC. - - Deletes a single ClientTlsPolicy. - - Returns: - Callable[[~.DeleteClientTlsPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_client_tls_policy' not in self._stubs: - self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.NetworkSecurity/DeleteClientTlsPolicy', - request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_client_tls_policy'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_authorization_policies: self._wrap_method( - self.list_authorization_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_authorization_policy: self._wrap_method( - self.get_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_authorization_policy: self._wrap_method( - self.create_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_authorization_policy: self._wrap_method( - self.update_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_authorization_policy: self._wrap_method( - self.delete_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_server_tls_policies: self._wrap_method( - self.list_server_tls_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_server_tls_policy: self._wrap_method( - self.get_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_server_tls_policy: self._wrap_method( - self.create_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_server_tls_policy: self._wrap_method( - self.update_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_server_tls_policy: self._wrap_method( - self.delete_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_client_tls_policies: self._wrap_method( - self.list_client_tls_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_client_tls_policy: self._wrap_method( - self.get_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_client_tls_policy: self._wrap_method( - self.create_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_client_tls_policy: self._wrap_method( - self.update_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_client_tls_policy: self._wrap_method( - self.delete_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'NetworkSecurityGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest.py deleted file mode 100644 index 9f69f839923d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest.py +++ /dev/null @@ -1,4105 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 -import google.protobuf - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.network_security_v1.types import authorization_policy -from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1.types import client_tls_policy -from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseNetworkSecurityRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class NetworkSecurityRestInterceptor: - """Interceptor for NetworkSecurity. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the NetworkSecurityRestTransport. - - .. code-block:: python - class MyCustomNetworkSecurityInterceptor(NetworkSecurityRestInterceptor): - def pre_create_authorization_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_authorization_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_client_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_client_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_server_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_server_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_authorization_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_authorization_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_client_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_client_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_server_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_server_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_authorization_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_authorization_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_client_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_client_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_server_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_server_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_authorization_policies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_authorization_policies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_client_tls_policies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_client_tls_policies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_server_tls_policies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_server_tls_policies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_authorization_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_authorization_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_client_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_client_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_server_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_server_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - transport = NetworkSecurityRestTransport(interceptor=MyCustomNetworkSecurityInterceptor()) - client = NetworkSecurityClient(transport=transport) - - - """ - def pre_create_authorization_policy(self, request: gcn_authorization_policy.CreateAuthorizationPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_authorization_policy.CreateAuthorizationPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_authorization_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_create_authorization_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_authorization_policy - - DEPRECATED. Please use the `post_create_authorization_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_create_authorization_policy` interceptor runs - before the `post_create_authorization_policy_with_metadata` interceptor. - """ - return response - - def post_create_authorization_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_authorization_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_create_authorization_policy_with_metadata` - interceptor in new development instead of the `post_create_authorization_policy` interceptor. - When both interceptors are used, this `post_create_authorization_policy_with_metadata` interceptor runs after the - `post_create_authorization_policy` interceptor. The (possibly modified) response returned by - `post_create_authorization_policy` will be passed to - `post_create_authorization_policy_with_metadata`. - """ - return response, metadata - - def pre_create_client_tls_policy(self, request: gcn_client_tls_policy.CreateClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_client_tls_policy.CreateClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_client_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_create_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_client_tls_policy - - DEPRECATED. Please use the `post_create_client_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_create_client_tls_policy` interceptor runs - before the `post_create_client_tls_policy_with_metadata` interceptor. - """ - return response - - def post_create_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_client_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_create_client_tls_policy_with_metadata` - interceptor in new development instead of the `post_create_client_tls_policy` interceptor. - When both interceptors are used, this `post_create_client_tls_policy_with_metadata` interceptor runs after the - `post_create_client_tls_policy` interceptor. The (possibly modified) response returned by - `post_create_client_tls_policy` will be passed to - `post_create_client_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_create_server_tls_policy(self, request: gcn_server_tls_policy.CreateServerTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_server_tls_policy.CreateServerTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_server_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_create_server_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_server_tls_policy - - DEPRECATED. Please use the `post_create_server_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_create_server_tls_policy` interceptor runs - before the `post_create_server_tls_policy_with_metadata` interceptor. - """ - return response - - def post_create_server_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_server_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_create_server_tls_policy_with_metadata` - interceptor in new development instead of the `post_create_server_tls_policy` interceptor. - When both interceptors are used, this `post_create_server_tls_policy_with_metadata` interceptor runs after the - `post_create_server_tls_policy` interceptor. The (possibly modified) response returned by - `post_create_server_tls_policy` will be passed to - `post_create_server_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_delete_authorization_policy(self, request: authorization_policy.DeleteAuthorizationPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[authorization_policy.DeleteAuthorizationPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_authorization_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_delete_authorization_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_authorization_policy - - DEPRECATED. Please use the `post_delete_authorization_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_delete_authorization_policy` interceptor runs - before the `post_delete_authorization_policy_with_metadata` interceptor. - """ - return response - - def post_delete_authorization_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for delete_authorization_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_delete_authorization_policy_with_metadata` - interceptor in new development instead of the `post_delete_authorization_policy` interceptor. - When both interceptors are used, this `post_delete_authorization_policy_with_metadata` interceptor runs after the - `post_delete_authorization_policy` interceptor. The (possibly modified) response returned by - `post_delete_authorization_policy` will be passed to - `post_delete_authorization_policy_with_metadata`. - """ - return response, metadata - - def pre_delete_client_tls_policy(self, request: client_tls_policy.DeleteClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.DeleteClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_client_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_delete_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_client_tls_policy - - DEPRECATED. Please use the `post_delete_client_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_delete_client_tls_policy` interceptor runs - before the `post_delete_client_tls_policy_with_metadata` interceptor. - """ - return response - - def post_delete_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for delete_client_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_delete_client_tls_policy_with_metadata` - interceptor in new development instead of the `post_delete_client_tls_policy` interceptor. - When both interceptors are used, this `post_delete_client_tls_policy_with_metadata` interceptor runs after the - `post_delete_client_tls_policy` interceptor. The (possibly modified) response returned by - `post_delete_client_tls_policy` will be passed to - `post_delete_client_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_delete_server_tls_policy(self, request: server_tls_policy.DeleteServerTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[server_tls_policy.DeleteServerTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_server_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_delete_server_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_server_tls_policy - - DEPRECATED. Please use the `post_delete_server_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_delete_server_tls_policy` interceptor runs - before the `post_delete_server_tls_policy_with_metadata` interceptor. - """ - return response - - def post_delete_server_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for delete_server_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_delete_server_tls_policy_with_metadata` - interceptor in new development instead of the `post_delete_server_tls_policy` interceptor. - When both interceptors are used, this `post_delete_server_tls_policy_with_metadata` interceptor runs after the - `post_delete_server_tls_policy` interceptor. The (possibly modified) response returned by - `post_delete_server_tls_policy` will be passed to - `post_delete_server_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_get_authorization_policy(self, request: authorization_policy.GetAuthorizationPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[authorization_policy.GetAuthorizationPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_authorization_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_get_authorization_policy(self, response: authorization_policy.AuthorizationPolicy) -> authorization_policy.AuthorizationPolicy: - """Post-rpc interceptor for get_authorization_policy - - DEPRECATED. Please use the `post_get_authorization_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_get_authorization_policy` interceptor runs - before the `post_get_authorization_policy_with_metadata` interceptor. - """ - return response - - def post_get_authorization_policy_with_metadata(self, response: authorization_policy.AuthorizationPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[authorization_policy.AuthorizationPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_authorization_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_get_authorization_policy_with_metadata` - interceptor in new development instead of the `post_get_authorization_policy` interceptor. - When both interceptors are used, this `post_get_authorization_policy_with_metadata` interceptor runs after the - `post_get_authorization_policy` interceptor. The (possibly modified) response returned by - `post_get_authorization_policy` will be passed to - `post_get_authorization_policy_with_metadata`. - """ - return response, metadata - - def pre_get_client_tls_policy(self, request: client_tls_policy.GetClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.GetClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_client_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_get_client_tls_policy(self, response: client_tls_policy.ClientTlsPolicy) -> client_tls_policy.ClientTlsPolicy: - """Post-rpc interceptor for get_client_tls_policy - - DEPRECATED. Please use the `post_get_client_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_get_client_tls_policy` interceptor runs - before the `post_get_client_tls_policy_with_metadata` interceptor. - """ - return response - - def post_get_client_tls_policy_with_metadata(self, response: client_tls_policy.ClientTlsPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ClientTlsPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_client_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_get_client_tls_policy_with_metadata` - interceptor in new development instead of the `post_get_client_tls_policy` interceptor. - When both interceptors are used, this `post_get_client_tls_policy_with_metadata` interceptor runs after the - `post_get_client_tls_policy` interceptor. The (possibly modified) response returned by - `post_get_client_tls_policy` will be passed to - `post_get_client_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_get_server_tls_policy(self, request: server_tls_policy.GetServerTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[server_tls_policy.GetServerTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_server_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_get_server_tls_policy(self, response: server_tls_policy.ServerTlsPolicy) -> server_tls_policy.ServerTlsPolicy: - """Post-rpc interceptor for get_server_tls_policy - - DEPRECATED. Please use the `post_get_server_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_get_server_tls_policy` interceptor runs - before the `post_get_server_tls_policy_with_metadata` interceptor. - """ - return response - - def post_get_server_tls_policy_with_metadata(self, response: server_tls_policy.ServerTlsPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[server_tls_policy.ServerTlsPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_server_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_get_server_tls_policy_with_metadata` - interceptor in new development instead of the `post_get_server_tls_policy` interceptor. - When both interceptors are used, this `post_get_server_tls_policy_with_metadata` interceptor runs after the - `post_get_server_tls_policy` interceptor. The (possibly modified) response returned by - `post_get_server_tls_policy` will be passed to - `post_get_server_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_list_authorization_policies(self, request: authorization_policy.ListAuthorizationPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[authorization_policy.ListAuthorizationPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_authorization_policies - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_list_authorization_policies(self, response: authorization_policy.ListAuthorizationPoliciesResponse) -> authorization_policy.ListAuthorizationPoliciesResponse: - """Post-rpc interceptor for list_authorization_policies - - DEPRECATED. Please use the `post_list_authorization_policies_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_list_authorization_policies` interceptor runs - before the `post_list_authorization_policies_with_metadata` interceptor. - """ - return response - - def post_list_authorization_policies_with_metadata(self, response: authorization_policy.ListAuthorizationPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[authorization_policy.ListAuthorizationPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_authorization_policies - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_list_authorization_policies_with_metadata` - interceptor in new development instead of the `post_list_authorization_policies` interceptor. - When both interceptors are used, this `post_list_authorization_policies_with_metadata` interceptor runs after the - `post_list_authorization_policies` interceptor. The (possibly modified) response returned by - `post_list_authorization_policies` will be passed to - `post_list_authorization_policies_with_metadata`. - """ - return response, metadata - - def pre_list_client_tls_policies(self, request: client_tls_policy.ListClientTlsPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ListClientTlsPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_client_tls_policies - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_list_client_tls_policies(self, response: client_tls_policy.ListClientTlsPoliciesResponse) -> client_tls_policy.ListClientTlsPoliciesResponse: - """Post-rpc interceptor for list_client_tls_policies - - DEPRECATED. Please use the `post_list_client_tls_policies_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_list_client_tls_policies` interceptor runs - before the `post_list_client_tls_policies_with_metadata` interceptor. - """ - return response - - def post_list_client_tls_policies_with_metadata(self, response: client_tls_policy.ListClientTlsPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ListClientTlsPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_client_tls_policies - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_list_client_tls_policies_with_metadata` - interceptor in new development instead of the `post_list_client_tls_policies` interceptor. - When both interceptors are used, this `post_list_client_tls_policies_with_metadata` interceptor runs after the - `post_list_client_tls_policies` interceptor. The (possibly modified) response returned by - `post_list_client_tls_policies` will be passed to - `post_list_client_tls_policies_with_metadata`. - """ - return response, metadata - - def pre_list_server_tls_policies(self, request: server_tls_policy.ListServerTlsPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[server_tls_policy.ListServerTlsPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_server_tls_policies - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_list_server_tls_policies(self, response: server_tls_policy.ListServerTlsPoliciesResponse) -> server_tls_policy.ListServerTlsPoliciesResponse: - """Post-rpc interceptor for list_server_tls_policies - - DEPRECATED. Please use the `post_list_server_tls_policies_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_list_server_tls_policies` interceptor runs - before the `post_list_server_tls_policies_with_metadata` interceptor. - """ - return response - - def post_list_server_tls_policies_with_metadata(self, response: server_tls_policy.ListServerTlsPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[server_tls_policy.ListServerTlsPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_server_tls_policies - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_list_server_tls_policies_with_metadata` - interceptor in new development instead of the `post_list_server_tls_policies` interceptor. - When both interceptors are used, this `post_list_server_tls_policies_with_metadata` interceptor runs after the - `post_list_server_tls_policies` interceptor. The (possibly modified) response returned by - `post_list_server_tls_policies` will be passed to - `post_list_server_tls_policies_with_metadata`. - """ - return response, metadata - - def pre_update_authorization_policy(self, request: gcn_authorization_policy.UpdateAuthorizationPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_authorization_policy.UpdateAuthorizationPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_authorization_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_update_authorization_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_authorization_policy - - DEPRECATED. Please use the `post_update_authorization_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_update_authorization_policy` interceptor runs - before the `post_update_authorization_policy_with_metadata` interceptor. - """ - return response - - def post_update_authorization_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_authorization_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_update_authorization_policy_with_metadata` - interceptor in new development instead of the `post_update_authorization_policy` interceptor. - When both interceptors are used, this `post_update_authorization_policy_with_metadata` interceptor runs after the - `post_update_authorization_policy` interceptor. The (possibly modified) response returned by - `post_update_authorization_policy` will be passed to - `post_update_authorization_policy_with_metadata`. - """ - return response, metadata - - def pre_update_client_tls_policy(self, request: gcn_client_tls_policy.UpdateClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_client_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_update_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_client_tls_policy - - DEPRECATED. Please use the `post_update_client_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_update_client_tls_policy` interceptor runs - before the `post_update_client_tls_policy_with_metadata` interceptor. - """ - return response - - def post_update_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_client_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_update_client_tls_policy_with_metadata` - interceptor in new development instead of the `post_update_client_tls_policy` interceptor. - When both interceptors are used, this `post_update_client_tls_policy_with_metadata` interceptor runs after the - `post_update_client_tls_policy` interceptor. The (possibly modified) response returned by - `post_update_client_tls_policy` will be passed to - `post_update_client_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_update_server_tls_policy(self, request: gcn_server_tls_policy.UpdateServerTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_server_tls_policy.UpdateServerTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_server_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_update_server_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_server_tls_policy - - DEPRECATED. Please use the `post_update_server_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_update_server_tls_policy` interceptor runs - before the `post_update_server_tls_policy_with_metadata` interceptor. - """ - return response - - def post_update_server_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_server_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_update_server_tls_policy_with_metadata` - interceptor in new development instead of the `post_update_server_tls_policy` interceptor. - When both interceptors are used, this `post_update_server_tls_policy_with_metadata` interceptor runs after the - `post_update_server_tls_policy` interceptor. The (possibly modified) response returned by - `post_update_server_tls_policy` will be passed to - `post_update_server_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class NetworkSecurityRestStub: - _session: AuthorizedSession - _host: str - _interceptor: NetworkSecurityRestInterceptor - - -class NetworkSecurityRestTransport(_BaseNetworkSecurityRestTransport): - """REST backend synchronous transport for NetworkSecurity. - - Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[NetworkSecurityRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or NetworkSecurityRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateAuthorizationPolicy(_BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.CreateAuthorizationPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: gcn_authorization_policy.CreateAuthorizationPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create authorization - policy method over HTTP. - - Args: - request (~.gcn_authorization_policy.CreateAuthorizationPolicyRequest): - The request object. Request used by the - CreateAuthorizationPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_http_options() - - request, metadata = self._interceptor.pre_create_authorization_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.CreateAuthorizationPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "CreateAuthorizationPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._CreateAuthorizationPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_authorization_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_authorization_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.create_authorization_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "CreateAuthorizationPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.CreateClientTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: gcn_client_tls_policy.CreateClientTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create client tls policy method over HTTP. - - Args: - request (~.gcn_client_tls_policy.CreateClientTlsPolicyRequest): - The request object. Request used by the - CreateClientTlsPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_create_client_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.CreateClientTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "CreateClientTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._CreateClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_client_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_client_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.create_client_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "CreateClientTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateServerTlsPolicy(_BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.CreateServerTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: gcn_server_tls_policy.CreateServerTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create server tls policy method over HTTP. - - Args: - request (~.gcn_server_tls_policy.CreateServerTlsPolicyRequest): - The request object. Request used by the - CreateServerTlsPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_create_server_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.CreateServerTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "CreateServerTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._CreateServerTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_server_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_server_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.create_server_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "CreateServerTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteAuthorizationPolicy(_BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.DeleteAuthorizationPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: authorization_policy.DeleteAuthorizationPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete authorization - policy method over HTTP. - - Args: - request (~.authorization_policy.DeleteAuthorizationPolicyRequest): - The request object. Request used by the - DeleteAuthorizationPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_http_options() - - request, metadata = self._interceptor.pre_delete_authorization_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.DeleteAuthorizationPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "DeleteAuthorizationPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._DeleteAuthorizationPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_delete_authorization_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_authorization_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.delete_authorization_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "DeleteAuthorizationPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.DeleteClientTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: client_tls_policy.DeleteClientTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete client tls policy method over HTTP. - - Args: - request (~.client_tls_policy.DeleteClientTlsPolicyRequest): - The request object. Request used by the - DeleteClientTlsPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_delete_client_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.DeleteClientTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "DeleteClientTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._DeleteClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_delete_client_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_client_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.delete_client_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "DeleteClientTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteServerTlsPolicy(_BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.DeleteServerTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: server_tls_policy.DeleteServerTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete server tls policy method over HTTP. - - Args: - request (~.server_tls_policy.DeleteServerTlsPolicyRequest): - The request object. Request used by the - DeleteServerTlsPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_delete_server_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.DeleteServerTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "DeleteServerTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._DeleteServerTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_delete_server_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_server_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.delete_server_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "DeleteServerTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetAuthorizationPolicy(_BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.GetAuthorizationPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: authorization_policy.GetAuthorizationPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> authorization_policy.AuthorizationPolicy: - r"""Call the get authorization policy method over HTTP. - - Args: - request (~.authorization_policy.GetAuthorizationPolicyRequest): - The request object. Request used by the - GetAuthorizationPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.authorization_policy.AuthorizationPolicy: - AuthorizationPolicy is a resource - that specifies how a server should - authorize incoming connections. This - resource in itself does not change the - configuration unless it's attached to a - target https proxy or endpoint config - selector resource. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_http_options() - - request, metadata = self._interceptor.pre_get_authorization_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetAuthorizationPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetAuthorizationPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._GetAuthorizationPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = authorization_policy.AuthorizationPolicy() - pb_resp = authorization_policy.AuthorizationPolicy.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_authorization_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_authorization_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = authorization_policy.AuthorizationPolicy.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.get_authorization_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetAuthorizationPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.GetClientTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: client_tls_policy.GetClientTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> client_tls_policy.ClientTlsPolicy: - r"""Call the get client tls policy method over HTTP. - - Args: - request (~.client_tls_policy.GetClientTlsPolicyRequest): - The request object. Request used by the - GetClientTlsPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.client_tls_policy.ClientTlsPolicy: - ClientTlsPolicy is a resource that - specifies how a client should - authenticate connections to backends of - a service. This resource itself does not - affect configuration unless it is - attached to a backend service resource. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_get_client_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetClientTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetClientTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._GetClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = client_tls_policy.ClientTlsPolicy() - pb_resp = client_tls_policy.ClientTlsPolicy.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_client_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_client_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = client_tls_policy.ClientTlsPolicy.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.get_client_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetClientTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetServerTlsPolicy(_BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.GetServerTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: server_tls_policy.GetServerTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> server_tls_policy.ServerTlsPolicy: - r"""Call the get server tls policy method over HTTP. - - Args: - request (~.server_tls_policy.GetServerTlsPolicyRequest): - The request object. Request used by the - GetServerTlsPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.server_tls_policy.ServerTlsPolicy: - ServerTlsPolicy is a resource that - specifies how a server should - authenticate incoming requests. This - resource itself does not affect - configuration unless it is attached to a - target https proxy or endpoint config - selector resource. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_get_server_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetServerTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetServerTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._GetServerTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = server_tls_policy.ServerTlsPolicy() - pb_resp = server_tls_policy.ServerTlsPolicy.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_server_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_server_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = server_tls_policy.ServerTlsPolicy.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.get_server_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetServerTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListAuthorizationPolicies(_BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.ListAuthorizationPolicies") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: authorization_policy.ListAuthorizationPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> authorization_policy.ListAuthorizationPoliciesResponse: - r"""Call the list authorization - policies method over HTTP. - - Args: - request (~.authorization_policy.ListAuthorizationPoliciesRequest): - The request object. Request used with the - ListAuthorizationPolicies method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.authorization_policy.ListAuthorizationPoliciesResponse: - Response returned by the - ListAuthorizationPolicies method. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_http_options() - - request, metadata = self._interceptor.pre_list_authorization_policies(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.ListAuthorizationPolicies", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "ListAuthorizationPolicies", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._ListAuthorizationPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = authorization_policy.ListAuthorizationPoliciesResponse() - pb_resp = authorization_policy.ListAuthorizationPoliciesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_authorization_policies(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_authorization_policies_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = authorization_policy.ListAuthorizationPoliciesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.list_authorization_policies", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "ListAuthorizationPolicies", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListClientTlsPolicies(_BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.ListClientTlsPolicies") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: client_tls_policy.ListClientTlsPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> client_tls_policy.ListClientTlsPoliciesResponse: - r"""Call the list client tls policies method over HTTP. - - Args: - request (~.client_tls_policy.ListClientTlsPoliciesRequest): - The request object. Request used by the - ListClientTlsPolicies method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.client_tls_policy.ListClientTlsPoliciesResponse: - Response returned by the - ListClientTlsPolicies method. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_http_options() - - request, metadata = self._interceptor.pre_list_client_tls_policies(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.ListClientTlsPolicies", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "ListClientTlsPolicies", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._ListClientTlsPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = client_tls_policy.ListClientTlsPoliciesResponse() - pb_resp = client_tls_policy.ListClientTlsPoliciesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_client_tls_policies(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_client_tls_policies_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = client_tls_policy.ListClientTlsPoliciesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.list_client_tls_policies", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "ListClientTlsPolicies", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListServerTlsPolicies(_BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.ListServerTlsPolicies") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: server_tls_policy.ListServerTlsPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> server_tls_policy.ListServerTlsPoliciesResponse: - r"""Call the list server tls policies method over HTTP. - - Args: - request (~.server_tls_policy.ListServerTlsPoliciesRequest): - The request object. Request used by the - ListServerTlsPolicies method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.server_tls_policy.ListServerTlsPoliciesResponse: - Response returned by the - ListServerTlsPolicies method. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_http_options() - - request, metadata = self._interceptor.pre_list_server_tls_policies(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.ListServerTlsPolicies", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "ListServerTlsPolicies", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._ListServerTlsPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = server_tls_policy.ListServerTlsPoliciesResponse() - pb_resp = server_tls_policy.ListServerTlsPoliciesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_server_tls_policies(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_server_tls_policies_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = server_tls_policy.ListServerTlsPoliciesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.list_server_tls_policies", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "ListServerTlsPolicies", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateAuthorizationPolicy(_BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.UpdateAuthorizationPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: gcn_authorization_policy.UpdateAuthorizationPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update authorization - policy method over HTTP. - - Args: - request (~.gcn_authorization_policy.UpdateAuthorizationPolicyRequest): - The request object. Request used by the - UpdateAuthorizationPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_http_options() - - request, metadata = self._interceptor.pre_update_authorization_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.UpdateAuthorizationPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "UpdateAuthorizationPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._UpdateAuthorizationPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_authorization_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_authorization_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.update_authorization_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "UpdateAuthorizationPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.UpdateClientTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: gcn_client_tls_policy.UpdateClientTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update client tls policy method over HTTP. - - Args: - request (~.gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - The request object. Request used by UpdateClientTlsPolicy - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_update_client_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.UpdateClientTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "UpdateClientTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._UpdateClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_client_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_client_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.update_client_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "UpdateClientTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateServerTlsPolicy(_BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.UpdateServerTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: gcn_server_tls_policy.UpdateServerTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update server tls policy method over HTTP. - - Args: - request (~.gcn_server_tls_policy.UpdateServerTlsPolicyRequest): - The request object. Request used by UpdateServerTlsPolicy - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_update_server_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.UpdateServerTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "UpdateServerTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._UpdateServerTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_server_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_server_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityClient.update_server_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "UpdateServerTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.CreateAuthorizationPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateAuthorizationPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.CreateServerTlsPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateServerTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_authorization_policy(self) -> Callable[ - [authorization_policy.DeleteAuthorizationPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteAuthorizationPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_server_tls_policy(self) -> Callable[ - [server_tls_policy.DeleteServerTlsPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteServerTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_authorization_policy(self) -> Callable[ - [authorization_policy.GetAuthorizationPolicyRequest], - authorization_policy.AuthorizationPolicy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetAuthorizationPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - client_tls_policy.ClientTlsPolicy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_server_tls_policy(self) -> Callable[ - [server_tls_policy.GetServerTlsPolicyRequest], - server_tls_policy.ServerTlsPolicy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetServerTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_authorization_policies(self) -> Callable[ - [authorization_policy.ListAuthorizationPoliciesRequest], - authorization_policy.ListAuthorizationPoliciesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListAuthorizationPolicies(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - client_tls_policy.ListClientTlsPoliciesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListClientTlsPolicies(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_server_tls_policies(self) -> Callable[ - [server_tls_policy.ListServerTlsPoliciesRequest], - server_tls_policy.ListServerTlsPoliciesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListServerTlsPolicies(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateAuthorizationPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateServerTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseNetworkSecurityRestTransport._BaseGetLocation, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_http_options() - - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetLocation", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetLocation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.GetLocation", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetLocation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseNetworkSecurityRestTransport._BaseListLocations, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseListLocations._get_http_options() - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.ListLocations", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "ListLocations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.ListLocations", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "ListLocations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseNetworkSecurityRestTransport._BaseGetIamPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_http_options() - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetIamPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.GetIamPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseNetworkSecurityRestTransport._BaseSetIamPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_http_options() - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.SetIamPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "SetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.SetIamPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "SetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseNetworkSecurityRestTransport._BaseTestIamPermissions, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_http_options() - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.TestIamPermissions", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "TestIamPermissions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.TestIamPermissions", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "TestIamPermissions", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseNetworkSecurityRestTransport._BaseCancelOperation, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_http_options() - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.CancelOperation", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "CancelOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseNetworkSecurityRestTransport._BaseDeleteOperation, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_http_options() - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.DeleteOperation", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseNetworkSecurityRestTransport._BaseGetOperation, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.GetOperation", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.GetOperation", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "GetOperation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseNetworkSecurityRestTransport._BaseListOperations, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1.NetworkSecurityClient.ListOperations", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1.NetworkSecurityAsyncClient.ListOperations", - extra = { - "serviceName": "google.cloud.networksecurity.v1.NetworkSecurity", - "rpcName": "ListOperations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'NetworkSecurityRestTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest_base.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest_base.py deleted file mode 100644 index 9742866a51ed..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/network_security/transports/rest_base.py +++ /dev/null @@ -1,1036 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.network_security_v1.types import authorization_policy -from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1.types import client_tls_policy -from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseNetworkSecurityRestTransport(NetworkSecurityTransport): - """Base REST backend transport for NetworkSecurity. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - credentials (Optional[Any]): 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. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseCreateAuthorizationPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "authorizationPolicyId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/authorizationPolicies', - 'body': 'authorization_policy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gcn_authorization_policy.CreateAuthorizationPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseCreateAuthorizationPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateClientTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "clientTlsPolicyId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/clientTlsPolicies', - 'body': 'client_tls_policy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateServerTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "serverTlsPolicyId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/serverTlsPolicies', - 'body': 'server_tls_policy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gcn_server_tls_policy.CreateServerTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseCreateServerTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteAuthorizationPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/authorizationPolicies/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = authorization_policy.DeleteAuthorizationPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseDeleteAuthorizationPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteClientTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/clientTlsPolicies/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = client_tls_policy.DeleteClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteServerTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/serverTlsPolicies/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = server_tls_policy.DeleteServerTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseDeleteServerTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetAuthorizationPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/authorizationPolicies/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = authorization_policy.GetAuthorizationPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseGetAuthorizationPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetClientTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/clientTlsPolicies/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = client_tls_policy.GetClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetServerTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/serverTlsPolicies/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = server_tls_policy.GetServerTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseGetServerTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListAuthorizationPolicies: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/authorizationPolicies', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = authorization_policy.ListAuthorizationPoliciesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseListAuthorizationPolicies._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListClientTlsPolicies: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/clientTlsPolicies', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = client_tls_policy.ListClientTlsPoliciesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListServerTlsPolicies: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/serverTlsPolicies', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = server_tls_policy.ListServerTlsPoliciesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseListServerTlsPolicies._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateAuthorizationPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{authorization_policy.name=projects/*/locations/*/authorizationPolicies/*}', - 'body': 'authorization_policy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseUpdateAuthorizationPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateClientTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}', - 'body': 'client_tls_policy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateServerTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{server_tls_policy.name=projects/*/locations/*/serverTlsPolicies/*}', - 'body': 'server_tls_policy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseUpdateServerTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLocation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListLocations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseCancelOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseDeleteOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListOperations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}/operations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseNetworkSecurityRestTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/__init__.py deleted file mode 100644 index 9198dadc54e6..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/__init__.py +++ /dev/null @@ -1,106 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .address_group import ( - AddAddressGroupItemsRequest, - AddressGroup, - CloneAddressGroupItemsRequest, - CreateAddressGroupRequest, - DeleteAddressGroupRequest, - GetAddressGroupRequest, - ListAddressGroupReferencesRequest, - ListAddressGroupReferencesResponse, - ListAddressGroupsRequest, - ListAddressGroupsResponse, - RemoveAddressGroupItemsRequest, - UpdateAddressGroupRequest, -) -from .authorization_policy import ( - AuthorizationPolicy, - CreateAuthorizationPolicyRequest, - DeleteAuthorizationPolicyRequest, - GetAuthorizationPolicyRequest, - ListAuthorizationPoliciesRequest, - ListAuthorizationPoliciesResponse, - UpdateAuthorizationPolicyRequest, -) -from .client_tls_policy import ( - ClientTlsPolicy, - CreateClientTlsPolicyRequest, - DeleteClientTlsPolicyRequest, - GetClientTlsPolicyRequest, - ListClientTlsPoliciesRequest, - ListClientTlsPoliciesResponse, - UpdateClientTlsPolicyRequest, -) -from .common import ( - OperationMetadata, -) -from .server_tls_policy import ( - CreateServerTlsPolicyRequest, - DeleteServerTlsPolicyRequest, - GetServerTlsPolicyRequest, - ListServerTlsPoliciesRequest, - ListServerTlsPoliciesResponse, - ServerTlsPolicy, - UpdateServerTlsPolicyRequest, -) -from .tls import ( - CertificateProvider, - CertificateProviderInstance, - GrpcEndpoint, - ValidationCA, -) - -__all__ = ( - 'AddAddressGroupItemsRequest', - 'AddressGroup', - 'CloneAddressGroupItemsRequest', - 'CreateAddressGroupRequest', - 'DeleteAddressGroupRequest', - 'GetAddressGroupRequest', - 'ListAddressGroupReferencesRequest', - 'ListAddressGroupReferencesResponse', - 'ListAddressGroupsRequest', - 'ListAddressGroupsResponse', - 'RemoveAddressGroupItemsRequest', - 'UpdateAddressGroupRequest', - 'AuthorizationPolicy', - 'CreateAuthorizationPolicyRequest', - 'DeleteAuthorizationPolicyRequest', - 'GetAuthorizationPolicyRequest', - 'ListAuthorizationPoliciesRequest', - 'ListAuthorizationPoliciesResponse', - 'UpdateAuthorizationPolicyRequest', - 'ClientTlsPolicy', - 'CreateClientTlsPolicyRequest', - 'DeleteClientTlsPolicyRequest', - 'GetClientTlsPolicyRequest', - 'ListClientTlsPoliciesRequest', - 'ListClientTlsPoliciesResponse', - 'UpdateClientTlsPolicyRequest', - 'OperationMetadata', - 'CreateServerTlsPolicyRequest', - 'DeleteServerTlsPolicyRequest', - 'GetServerTlsPolicyRequest', - 'ListServerTlsPoliciesRequest', - 'ListServerTlsPoliciesResponse', - 'ServerTlsPolicy', - 'UpdateServerTlsPolicyRequest', - 'CertificateProvider', - 'CertificateProviderInstance', - 'GrpcEndpoint', - 'ValidationCA', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/authorization_policy.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/authorization_policy.py deleted file mode 100644 index 7623a1508e63..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/authorization_policy.py +++ /dev/null @@ -1,425 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1', - manifest={ - 'AuthorizationPolicy', - 'ListAuthorizationPoliciesRequest', - 'ListAuthorizationPoliciesResponse', - 'GetAuthorizationPolicyRequest', - 'CreateAuthorizationPolicyRequest', - 'UpdateAuthorizationPolicyRequest', - 'DeleteAuthorizationPolicyRequest', - }, -) - - -class AuthorizationPolicy(proto.Message): - r"""AuthorizationPolicy is a resource that specifies how a server - should authorize incoming connections. This resource in itself - does not change the configuration unless it's attached to a - target https proxy or endpoint config selector resource. - - Attributes: - name (str): - Required. Name of the AuthorizationPolicy resource. It - matches pattern - ``projects/{project}/locations/{location}/authorizationPolicies/``. - description (str): - Optional. Free-text description of the - resource. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was updated. - labels (MutableMapping[str, str]): - Optional. Set of label tags associated with - the AuthorizationPolicy resource. - action (google.cloud.network_security_v1.types.AuthorizationPolicy.Action): - Required. The action to take when a rule - match is found. Possible values are "ALLOW" or - "DENY". - rules (MutableSequence[google.cloud.network_security_v1.types.AuthorizationPolicy.Rule]): - Optional. List of rules to match. Note that at least one of - the rules must match in order for the action specified in - the 'action' field to be taken. A rule is a match if there - is a matching source and destination. If left blank, the - action specified in the ``action`` field will be applied on - every request. - """ - class Action(proto.Enum): - r"""Possible values that define what action to take. - - Values: - ACTION_UNSPECIFIED (0): - Default value. - ALLOW (1): - Grant access. - DENY (2): - Deny access. - Deny rules should be avoided unless they are - used to provide a default "deny all" fallback. - """ - ACTION_UNSPECIFIED = 0 - ALLOW = 1 - DENY = 2 - - class Rule(proto.Message): - r"""Specification of rules. - - Attributes: - sources (MutableSequence[google.cloud.network_security_v1.types.AuthorizationPolicy.Rule.Source]): - Optional. List of attributes for the traffic source. All of - the sources must match. A source is a match if both - principals and ip_blocks match. If not set, the action - specified in the 'action' field will be applied without any - rule checks for the source. - destinations (MutableSequence[google.cloud.network_security_v1.types.AuthorizationPolicy.Rule.Destination]): - Optional. List of attributes for the traffic - destination. All of the destinations must match. - A destination is a match if a request matches - all the specified hosts, ports, methods and - headers. If not set, the action specified in the - 'action' field will be applied without any rule - checks for the destination. - """ - - class Source(proto.Message): - r"""Specification of traffic source attributes. - - Attributes: - principals (MutableSequence[str]): - Optional. List of peer identities to match for - authorization. At least one principal should match. Each - peer can be an exact match, or a prefix match (example, - "namespace/*") or a suffix match (example, - "*/service-account") or a presence match "*". Authorization - based on the principal name without certificate validation - (configured by ServerTlsPolicy resource) is considered - insecure. - ip_blocks (MutableSequence[str]): - Optional. List of CIDR ranges to match based - on source IP address. At least one IP block - should match. Single IP (e.g., "1.2.3.4") and - CIDR (e.g., "1.2.3.0/24") are supported. - Authorization based on source IP alone should be - avoided. The IP addresses of any load balancers - or proxies should be considered untrusted. - """ - - principals: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - ip_blocks: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class Destination(proto.Message): - r"""Specification of traffic destination attributes. - - Attributes: - hosts (MutableSequence[str]): - Required. List of host names to match. Matched against the - ":authority" header in http requests. At least one host - should match. Each host can be an exact match, or a prefix - match (example "mydomain.*") or a suffix match (example - "*.myorg.com") or a presence (any) match "*". - ports (MutableSequence[int]): - Required. List of destination ports to match. - At least one port should match. - methods (MutableSequence[str]): - Optional. A list of HTTP methods to match. At - least one method should match. Should not be set - for gRPC services. - http_header_match (google.cloud.network_security_v1.types.AuthorizationPolicy.Rule.Destination.HttpHeaderMatch): - Optional. Match against key:value pair in - http header. Provides a flexible match based on - HTTP headers, for potentially advanced use - cases. At least one header should match. Avoid - using header matches to make authorization - decisions unless there is a strong guarantee - that requests arrive through a trusted client or - proxy. - """ - - class HttpHeaderMatch(proto.Message): - r"""Specification of HTTP header match attributes. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - regex_match (str): - Required. The value of the header must match - the regular expression specified in regexMatch. - For regular expression grammar, please see: - en.cppreference.com/w/cpp/regex/ecmascript For - matching against a port specified in the HTTP - request, use a headerMatch with headerName set - to Host and a regular expression that satisfies - the RFC2616 Host header's port specifier. - - This field is a member of `oneof`_ ``type``. - header_name (str): - Required. The name of the HTTP header to - match. For matching against the HTTP request's - authority, use a headerMatch with the header - name ":authority". For matching a request's - method, use the headerName ":method". - """ - - regex_match: str = proto.Field( - proto.STRING, - number=2, - oneof='type', - ) - header_name: str = proto.Field( - proto.STRING, - number=1, - ) - - hosts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - ports: MutableSequence[int] = proto.RepeatedField( - proto.UINT32, - number=2, - ) - methods: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - http_header_match: 'AuthorizationPolicy.Rule.Destination.HttpHeaderMatch' = proto.Field( - proto.MESSAGE, - number=5, - message='AuthorizationPolicy.Rule.Destination.HttpHeaderMatch', - ) - - sources: MutableSequence['AuthorizationPolicy.Rule.Source'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AuthorizationPolicy.Rule.Source', - ) - destinations: MutableSequence['AuthorizationPolicy.Rule.Destination'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AuthorizationPolicy.Rule.Destination', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - action: Action = proto.Field( - proto.ENUM, - number=6, - enum=Action, - ) - rules: MutableSequence[Rule] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Rule, - ) - - -class ListAuthorizationPoliciesRequest(proto.Message): - r"""Request used with the ListAuthorizationPolicies method. - - Attributes: - parent (str): - Required. The project and location from which the - AuthorizationPolicies should be listed, specified in the - format ``projects/{project}/locations/{location}``. - page_size (int): - Maximum number of AuthorizationPolicies to - return per call. - page_token (str): - The value returned by the last - ``ListAuthorizationPoliciesResponse`` Indicates that this is - a continuation of a prior ``ListAuthorizationPolicies`` - call, and that the system should return the next page of - data. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAuthorizationPoliciesResponse(proto.Message): - r"""Response returned by the ListAuthorizationPolicies method. - - Attributes: - authorization_policies (MutableSequence[google.cloud.network_security_v1.types.AuthorizationPolicy]): - List of AuthorizationPolicies resources. - next_page_token (str): - If there might be 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 - - authorization_policies: MutableSequence['AuthorizationPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AuthorizationPolicy', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetAuthorizationPolicyRequest(proto.Message): - r"""Request used by the GetAuthorizationPolicy method. - - Attributes: - name (str): - Required. A name of the AuthorizationPolicy to get. Must be - in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateAuthorizationPolicyRequest(proto.Message): - r"""Request used by the CreateAuthorizationPolicy method. - - Attributes: - parent (str): - Required. The parent resource of the AuthorizationPolicy. - Must be in the format - ``projects/{project}/locations/{location}``. - authorization_policy_id (str): - Required. Short name of the AuthorizationPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and underscores, - and should not start with a number. E.g. "authz_policy". - authorization_policy (google.cloud.network_security_v1.types.AuthorizationPolicy): - Required. AuthorizationPolicy resource to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - authorization_policy_id: str = proto.Field( - proto.STRING, - number=2, - ) - authorization_policy: 'AuthorizationPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='AuthorizationPolicy', - ) - - -class UpdateAuthorizationPolicyRequest(proto.Message): - r"""Request used by the UpdateAuthorizationPolicy method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the AuthorizationPolicy resource by the - update. The fields specified in the update_mask are relative - to the resource, not the full request. A field will be - overwritten if it is in the mask. If the user does not - provide a mask then all fields will be overwritten. - authorization_policy (google.cloud.network_security_v1.types.AuthorizationPolicy): - Required. Updated AuthorizationPolicy - resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - authorization_policy: 'AuthorizationPolicy' = proto.Field( - proto.MESSAGE, - number=2, - message='AuthorizationPolicy', - ) - - -class DeleteAuthorizationPolicyRequest(proto.Message): - r"""Request used by the DeleteAuthorizationPolicy method. - - Attributes: - name (str): - Required. A name of the AuthorizationPolicy to delete. Must - be in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/client_tls_policy.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/client_tls_policy.py deleted file mode 100644 index f18aeab942af..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/client_tls_policy.py +++ /dev/null @@ -1,271 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.network_security_v1.types import tls -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1', - manifest={ - 'ClientTlsPolicy', - 'ListClientTlsPoliciesRequest', - 'ListClientTlsPoliciesResponse', - 'GetClientTlsPolicyRequest', - 'CreateClientTlsPolicyRequest', - 'UpdateClientTlsPolicyRequest', - 'DeleteClientTlsPolicyRequest', - }, -) - - -class ClientTlsPolicy(proto.Message): - r"""ClientTlsPolicy is a resource that specifies how a client - should authenticate connections to backends of a service. This - resource itself does not affect configuration unless it is - attached to a backend service resource. - - Attributes: - name (str): - Required. Name of the ClientTlsPolicy resource. It matches - the pattern - ``projects/*/locations/{location}/clientTlsPolicies/{client_tls_policy}`` - description (str): - Optional. Free-text description of the - resource. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was updated. - labels (MutableMapping[str, str]): - Optional. Set of label tags associated with - the resource. - sni (str): - Optional. Server Name Indication string to - present to the server during TLS handshake. E.g: - "secure.example.com". - client_certificate (google.cloud.network_security_v1.types.CertificateProvider): - Optional. Defines a mechanism to provision - client identity (public and private keys) for - peer to peer authentication. The presence of - this dictates mTLS. - server_validation_ca (MutableSequence[google.cloud.network_security_v1.types.ValidationCA]): - Optional. Defines the mechanism to obtain the - Certificate Authority certificate to validate - the server certificate. If empty, client does - not validate the server certificate. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - sni: str = proto.Field( - proto.STRING, - number=6, - ) - client_certificate: tls.CertificateProvider = proto.Field( - proto.MESSAGE, - number=7, - message=tls.CertificateProvider, - ) - server_validation_ca: MutableSequence[tls.ValidationCA] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=tls.ValidationCA, - ) - - -class ListClientTlsPoliciesRequest(proto.Message): - r"""Request used by the ListClientTlsPolicies method. - - Attributes: - parent (str): - Required. The project and location from which the - ClientTlsPolicies should be listed, specified in the format - ``projects/*/locations/{location}``. - page_size (int): - Maximum number of ClientTlsPolicies to return - per call. - page_token (str): - The value returned by the last - ``ListClientTlsPoliciesResponse`` Indicates that this is a - continuation of a prior ``ListClientTlsPolicies`` call, and - that the system should return the next page of data. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListClientTlsPoliciesResponse(proto.Message): - r"""Response returned by the ListClientTlsPolicies method. - - Attributes: - client_tls_policies (MutableSequence[google.cloud.network_security_v1.types.ClientTlsPolicy]): - List of ClientTlsPolicy resources. - next_page_token (str): - If there might be 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 - - client_tls_policies: MutableSequence['ClientTlsPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ClientTlsPolicy', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetClientTlsPolicyRequest(proto.Message): - r"""Request used by the GetClientTlsPolicy method. - - Attributes: - name (str): - Required. A name of the ClientTlsPolicy to get. Must be in - the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateClientTlsPolicyRequest(proto.Message): - r"""Request used by the CreateClientTlsPolicy method. - - Attributes: - parent (str): - Required. The parent resource of the ClientTlsPolicy. Must - be in the format ``projects/*/locations/{location}``. - client_tls_policy_id (str): - Required. Short name of the ClientTlsPolicy resource to be - created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and underscores, - and should not start with a number. E.g. - "client_mtls_policy". - client_tls_policy (google.cloud.network_security_v1.types.ClientTlsPolicy): - Required. ClientTlsPolicy resource to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - client_tls_policy_id: str = proto.Field( - proto.STRING, - number=2, - ) - client_tls_policy: 'ClientTlsPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='ClientTlsPolicy', - ) - - -class UpdateClientTlsPolicyRequest(proto.Message): - r"""Request used by UpdateClientTlsPolicy method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the ClientTlsPolicy resource by the update. - The fields specified in the update_mask are relative to the - resource, not the full request. A field will be overwritten - if it is in the mask. If the user does not provide a mask - then all fields will be overwritten. - client_tls_policy (google.cloud.network_security_v1.types.ClientTlsPolicy): - Required. Updated ClientTlsPolicy resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - client_tls_policy: 'ClientTlsPolicy' = proto.Field( - proto.MESSAGE, - number=2, - message='ClientTlsPolicy', - ) - - -class DeleteClientTlsPolicyRequest(proto.Message): - r"""Request used by the DeleteClientTlsPolicy method. - - Attributes: - name (str): - Required. A name of the ClientTlsPolicy to delete. Must be - in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/common.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/common.py deleted file mode 100644 index 4fa7c372927d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/common.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1', - manifest={ - 'OperationMetadata', - }, -) - - -class OperationMetadata(proto.Message): - r"""Represents the metadata of the long-running operation. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation was - created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation finished - running. - target (str): - Output only. Server-defined resource path for - the target of the operation. - verb (str): - Output only. Name of the verb executed by the - operation. - status_message (str): - Output only. Human-readable status of the - operation, if any. - requested_cancellation (bool): - Output only. Identifies whether the user has requested - cancellation of the operation. Operations that have - successfully been cancelled have [Operation.error][] value - with a [google.rpc.Status.code][google.rpc.Status.code] of - 1, corresponding to ``Code.CANCELLED``. - api_version (str): - Output only. API version used to start the - operation. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/network_security.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/network_security.py deleted file mode 100644 index 3a1dee864b0f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/network_security.py +++ /dev/null @@ -1,26 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/server_tls_policy.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/server_tls_policy.py deleted file mode 100644 index ec702dcdd3d0..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/server_tls_policy.py +++ /dev/null @@ -1,296 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.network_security_v1.types import tls -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1', - manifest={ - 'ServerTlsPolicy', - 'ListServerTlsPoliciesRequest', - 'ListServerTlsPoliciesResponse', - 'GetServerTlsPolicyRequest', - 'CreateServerTlsPolicyRequest', - 'UpdateServerTlsPolicyRequest', - 'DeleteServerTlsPolicyRequest', - }, -) - - -class ServerTlsPolicy(proto.Message): - r"""ServerTlsPolicy is a resource that specifies how a server - should authenticate incoming requests. This resource itself does - not affect configuration unless it is attached to a target https - proxy or endpoint config selector resource. - - Attributes: - name (str): - Required. Name of the ServerTlsPolicy resource. It matches - the pattern - ``projects/*/locations/{location}/serverTlsPolicies/{server_tls_policy}`` - description (str): - Free-text description of the resource. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was updated. - labels (MutableMapping[str, str]): - Set of label tags associated with the - resource. - allow_open (bool): - Determines if server allows plaintext connections. If set to - true, server allows plain text connections. By default, it - is set to false. This setting is not exclusive of other - encryption modes. For example, if ``allow_open`` and - ``mtls_policy`` are set, server allows both plain text and - mTLS connections. See documentation of other encryption - modes to confirm compatibility. - - Consider using it if you wish to upgrade in place your - deployment to TLS while having mixed TLS and non-TLS traffic - reaching port :80. - server_certificate (google.cloud.network_security_v1.types.CertificateProvider): - Defines a mechanism to provision server identity (public and - private keys). Cannot be combined with ``allow_open`` as a - permissive mode that allows both plain text and TLS is not - supported. - mtls_policy (google.cloud.network_security_v1.types.ServerTlsPolicy.MTLSPolicy): - Defines a mechanism to provision peer validation - certificates for peer to peer authentication (Mutual TLS - - mTLS). If not specified, client certificate will not be - requested. The connection is treated as TLS and not mTLS. If - ``allow_open`` and ``mtls_policy`` are set, server allows - both plain text and mTLS connections. - """ - - class MTLSPolicy(proto.Message): - r"""Specification of the MTLSPolicy. - - Attributes: - client_validation_ca (MutableSequence[google.cloud.network_security_v1.types.ValidationCA]): - Defines the mechanism to obtain the - Certificate Authority certificate to validate - the client certificate. - """ - - client_validation_ca: MutableSequence[tls.ValidationCA] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=tls.ValidationCA, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - allow_open: bool = proto.Field( - proto.BOOL, - number=6, - ) - server_certificate: tls.CertificateProvider = proto.Field( - proto.MESSAGE, - number=7, - message=tls.CertificateProvider, - ) - mtls_policy: MTLSPolicy = proto.Field( - proto.MESSAGE, - number=8, - message=MTLSPolicy, - ) - - -class ListServerTlsPoliciesRequest(proto.Message): - r"""Request used by the ListServerTlsPolicies method. - - Attributes: - parent (str): - Required. The project and location from which the - ServerTlsPolicies should be listed, specified in the format - ``projects/*/locations/{location}``. - page_size (int): - Maximum number of ServerTlsPolicies to return - per call. - page_token (str): - The value returned by the last - ``ListServerTlsPoliciesResponse`` Indicates that this is a - continuation of a prior ``ListServerTlsPolicies`` call, and - that the system should return the next page of data. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListServerTlsPoliciesResponse(proto.Message): - r"""Response returned by the ListServerTlsPolicies method. - - Attributes: - server_tls_policies (MutableSequence[google.cloud.network_security_v1.types.ServerTlsPolicy]): - List of ServerTlsPolicy resources. - next_page_token (str): - If there might be 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 - - server_tls_policies: MutableSequence['ServerTlsPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ServerTlsPolicy', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetServerTlsPolicyRequest(proto.Message): - r"""Request used by the GetServerTlsPolicy method. - - Attributes: - name (str): - Required. A name of the ServerTlsPolicy to get. Must be in - the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateServerTlsPolicyRequest(proto.Message): - r"""Request used by the CreateServerTlsPolicy method. - - Attributes: - parent (str): - Required. The parent resource of the ServerTlsPolicy. Must - be in the format ``projects/*/locations/{location}``. - server_tls_policy_id (str): - Required. Short name of the ServerTlsPolicy resource to be - created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and underscores, - and should not start with a number. E.g. - "server_mtls_policy". - server_tls_policy (google.cloud.network_security_v1.types.ServerTlsPolicy): - Required. ServerTlsPolicy resource to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - server_tls_policy_id: str = proto.Field( - proto.STRING, - number=2, - ) - server_tls_policy: 'ServerTlsPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='ServerTlsPolicy', - ) - - -class UpdateServerTlsPolicyRequest(proto.Message): - r"""Request used by UpdateServerTlsPolicy method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the ServerTlsPolicy resource by the update. - The fields specified in the update_mask are relative to the - resource, not the full request. A field will be overwritten - if it is in the mask. If the user does not provide a mask - then all fields will be overwritten. - server_tls_policy (google.cloud.network_security_v1.types.ServerTlsPolicy): - Required. Updated ServerTlsPolicy resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - server_tls_policy: 'ServerTlsPolicy' = proto.Field( - proto.MESSAGE, - number=2, - message='ServerTlsPolicy', - ) - - -class DeleteServerTlsPolicyRequest(proto.Message): - r"""Request used by the DeleteServerTlsPolicy method. - - Attributes: - name (str): - Required. A name of the ServerTlsPolicy to delete. Must be - in the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/tls.py b/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/tls.py deleted file mode 100644 index c1f555aa255e..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/tls.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1', - manifest={ - 'GrpcEndpoint', - 'ValidationCA', - 'CertificateProviderInstance', - 'CertificateProvider', - }, -) - - -class GrpcEndpoint(proto.Message): - r"""Specification of the GRPC Endpoint. - - Attributes: - target_uri (str): - Required. The target URI of the gRPC - endpoint. Only UDS path is supported, and should - start with "unix:". - """ - - target_uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ValidationCA(proto.Message): - r"""Specification of ValidationCA. Defines the mechanism to - obtain the Certificate Authority certificate to validate the - peer certificate. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - grpc_endpoint (google.cloud.network_security_v1.types.GrpcEndpoint): - gRPC specific configuration to access the - gRPC server to obtain the CA certificate. - - This field is a member of `oneof`_ ``type``. - certificate_provider_instance (google.cloud.network_security_v1.types.CertificateProviderInstance): - The certificate provider instance - specification that will be passed to the data - plane, which will be used to load necessary - credential information. - - This field is a member of `oneof`_ ``type``. - """ - - grpc_endpoint: 'GrpcEndpoint' = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message='GrpcEndpoint', - ) - certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( - proto.MESSAGE, - number=3, - oneof='type', - message='CertificateProviderInstance', - ) - - -class CertificateProviderInstance(proto.Message): - r"""Specification of a TLS certificate provider instance. - Workloads may have one or more CertificateProvider instances - (plugins) and one of them is enabled and configured by - specifying this message. Workloads use the values from this - message to locate and load the CertificateProvider instance - configuration. - - Attributes: - plugin_instance (str): - Required. Plugin instance name, used to locate and load - CertificateProvider instance configuration. Set to - "google_cloud_private_spiffe" to use Certificate Authority - Service certificate provider instance. - """ - - plugin_instance: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CertificateProvider(proto.Message): - r"""Specification of certificate provider. Defines the mechanism - to obtain the certificate and private key for peer to peer - authentication. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - grpc_endpoint (google.cloud.network_security_v1.types.GrpcEndpoint): - gRPC specific configuration to access the - gRPC server to obtain the cert and private key. - - This field is a member of `oneof`_ ``type``. - certificate_provider_instance (google.cloud.network_security_v1.types.CertificateProviderInstance): - The certificate provider instance - specification that will be passed to the data - plane, which will be used to load necessary - credential information. - - This field is a member of `oneof`_ ``type``. - """ - - grpc_endpoint: 'GrpcEndpoint' = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message='GrpcEndpoint', - ) - certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( - proto.MESSAGE, - number=3, - oneof='type', - message='CertificateProviderInstance', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1/mypy.ini b/owl-bot-staging/google-cloud-network-security/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-security/v1/noxfile.py b/owl-bot-staging/google-cloud-network-security/v1/noxfile.py deleted file mode 100644 index 6de174fa4528..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/noxfile.py +++ /dev/null @@ -1,592 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re -import shutil - -from typing import Dict, List -import warnings - -import nox - -BLACK_VERSION = "black[jupyter]==23.7.0" -ISORT_VERSION = "isort==5.11.0" - -LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = "google-cloud-network-security" - -UNIT_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "asyncmock", - "pytest", - "pytest-cov", - "pytest-asyncio", -] -UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_DEPENDENCIES: List[str] = [] -UNIT_TEST_EXTRAS: List[str] = [] -UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] -SYSTEM_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "pytest", - "google-cloud-testutils", -] -SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_EXTRAS: List[str] = [] -SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -nox.options.sessions = [ - "unit", - "system", - "cover", - "lint", - "lint_setup_py", - "blacken", - "docs", -] - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", - "types-requests", - "types-protobuf", - ) - session.install(".") - session.run( - "mypy", - "-p", - "google", - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "update", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "check", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *LINT_PATHS, - ) - - session.run("flake8", "google", "tests") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def format(session): - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run( - "isort", - "--fss", - *LINT_PATHS, - ) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("setuptools", "docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") - - -def install_unittest_dependencies(session, *constraints): - standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES - session.install(*standard_deps, *constraints) - - if UNIT_TEST_EXTERNAL_DEPENDENCIES: - warnings.warn( - "'unit_test_external_dependencies' is deprecated. Instead, please " - "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", - DeprecationWarning, - ) - session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_LOCAL_DEPENDENCIES: - session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_EXTRAS_BY_PYTHON: - extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif UNIT_TEST_EXTRAS: - extras = UNIT_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def unit(session, protobuf_implementation): - # Install all test dependencies, then install this package in-place. - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - install_unittest_dependencies(session, "-c", constraints_path) - - # TODO(https://github.com/googleapis/synthtool/issues/1976): - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - # Run py.test against the unit tests. - session.run( - "py.test", - "--quiet", - f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=google", - "--cov=tests/unit", - "--cov-append", - "--cov-config=.coveragerc", - "--cov-report=", - "--cov-fail-under=0", - os.path.join("tests", "unit"), - *session.posargs, - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -def install_systemtest_dependencies(session, *constraints): - session.install("--pre", "grpcio") - - session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: - session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_LOCAL_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTRAS_BY_PYTHON: - extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif SYSTEM_TEST_EXTRAS: - extras = SYSTEM_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) -def system(session): - """Run the system test suite.""" - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. - if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": - session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Install pyopenssl for mTLS testing. - if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": - session.install("pyopenssl") - - system_test_exists = os.path.exists(system_test_path) - system_test_folder_exists = os.path.exists(system_test_folder_path) - # Sanity check: only run tests if found. - if not system_test_exists and not system_test_folder_exists: - session.skip("System tests were not found") - - install_systemtest_dependencies(session, "-c", constraints_path) - - # Run py.test against the system tests. - if system_test_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if system_test_folder_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python="3.10") -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "sphinx==4.5.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", ""), - ) - - -@nox.session(python="3.10") -def docfx(session): - """Build the docfx yaml files for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "gcp-sphinx-docfx-yaml", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-D", - ( - "extensions=sphinx.ext.autodoc," - "sphinx.ext.autosummary," - "docfx_yaml.extension," - "sphinx.ext.intersphinx," - "sphinx.ext.coverage," - "sphinx.ext.napoleon," - "sphinx.ext.todo," - "sphinx.ext.viewcode," - "recommonmark" - ), - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def prerelease_deps(session, protobuf_implementation): - """ - Run all tests with pre-release versions of dependencies installed - rather than the standard non pre-release versions. - Pre-release versions can be installed using - `pip install --pre `. - """ - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # Note: If a dependency is added to the `prerel_deps` list, - # the `core_dependencies_from_source` list in the `core_deps_from_source` - # nox session should also be updated. - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpc-google-iam-v1", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--ignore-installed", dep) - # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` - # to the dictionary below once this bug is fixed. - # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add - # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below - # once this bug is fixed. - package_namespaces = { - "google-api-core": "google.api_core", - "google-auth": "google.auth", - "grpcio": "grpc", - "protobuf": "google.protobuf", - "proto-plus": "proto", - } - - version_namespace = package_namespaces.get(dep) - - print(f"Installed {dep}") - if version_namespace: - session.run( - "python", - "-c", - f"import {version_namespace}; print({version_namespace}.__version__)", - ) - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb"], -) -def core_deps_from_source(session, protobuf_implementation): - """Run all tests with core dependencies installed from source - rather than pulling the dependencies from PyPI. - """ - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and - # `grpcio-status` should be added to the list below so that they are installed from source, - # rather than PyPI. - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be - # added to the list below so that it is installed from source, rather than PyPI - # Note: If a dependency is added to the `core_dependencies_from_source` list, - # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. - core_dependencies_from_source = [ - "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", - "google-api-core @ git+https://github.com/googleapis/python-api-core.git", - "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", - "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", - "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", - ] - - for dep in core_dependencies_from_source: - session.install(dep, "--no-deps", "--ignore-installed") - print(f"Installed {dep}") - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_async.py deleted file mode 100644 index 278ecf0b53c5..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_create_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1.CreateAuthorizationPolicyRequest( - parent="parent_value", - authorization_policy_id="authorization_policy_id_value", - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.create_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_sync.py deleted file mode 100644 index 051baad08806..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_authorization_policy_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_create_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1.CreateAuthorizationPolicyRequest( - parent="parent_value", - authorization_policy_id="authorization_policy_id_value", - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.create_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_async.py deleted file mode 100644 index 0b07d2e09c29..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py deleted file mode 100644 index 071d42cea22a..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_async.py deleted file mode 100644 index 612746567f89..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_create_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1.CreateServerTlsPolicyRequest( - parent="parent_value", - server_tls_policy_id="server_tls_policy_id_value", - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.create_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py deleted file mode 100644 index ed0d9fe82ee7..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_create_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1.CreateServerTlsPolicyRequest( - parent="parent_value", - server_tls_policy_id="server_tls_policy_id_value", - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.create_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_async.py deleted file mode 100644 index 3ef46bc6d32b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_delete_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py deleted file mode 100644 index 310ed40682db..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_delete_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py deleted file mode 100644 index c54c066155b5..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py deleted file mode 100644 index b851622a0786..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py deleted file mode 100644 index d2098fe79352..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_delete_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py deleted file mode 100644 index 927c9547e922..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_delete_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.DeleteServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_async.py deleted file mode 100644 index 44e2152ba3b2..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_get_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.GetAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_authorization_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_sync.py deleted file mode 100644 index 04deb1cebc7b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_authorization_policy_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_get_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.GetAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_authorization_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_async.py deleted file mode 100644 index 979373defb01..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py deleted file mode 100644 index f0f70848bb82..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_async.py deleted file mode 100644 index 56f66e7ab8d9..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_get_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.GetServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_server_tls_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py deleted file mode 100644 index 48958304c033..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_get_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.GetServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_server_tls_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_async.py deleted file mode 100644 index 1a160a776672..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAuthorizationPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_list_authorization_policies(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.ListAuthorizationPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_authorization_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_sync.py deleted file mode 100644 index 714b743f9785..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_authorization_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAuthorizationPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_list_authorization_policies(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.ListAuthorizationPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_authorization_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_async.py deleted file mode 100644 index 02fb1c13e09b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListClientTlsPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py deleted file mode 100644 index 490f8df29a4d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListClientTlsPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_async.py deleted file mode 100644 index f89f216a0bb7..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServerTlsPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_list_server_tls_policies(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1.ListServerTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_server_tls_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py deleted file mode 100644 index 23d030a39f82..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServerTlsPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_list_server_tls_policies(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1.ListServerTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_server_tls_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_async.py deleted file mode 100644 index f859337f3e14..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_update_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1.UpdateAuthorizationPolicyRequest( - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.update_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_sync.py deleted file mode 100644 index 5f48db524947..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_authorization_policy_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_update_authorization_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1.UpdateAuthorizationPolicyRequest( - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.update_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_async.py deleted file mode 100644 index 428dfbcad4e0..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py deleted file mode 100644 index 9d1cf8fa461b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_async.py deleted file mode 100644 index f86aaa60c9f2..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -async def sample_update_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1.UpdateServerTlsPolicyRequest( - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.update_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py deleted file mode 100644 index 7a0fa59f57a1..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1 - - -def sample_update_server_tls_policy(): - # Create a client - client = network_security_v1.NetworkSecurityClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1.UpdateServerTlsPolicyRequest( - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.update_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json b/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json deleted file mode 100644 index ff3746a9796b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json +++ /dev/null @@ -1,5496 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.networksecurity.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-network-security", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", - "shortName": "AddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.add_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.AddAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "AddAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "items", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "add_address_group_items" - }, - "description": "Sample for AddAddressGroupItems", - "file": "networksecurity_v1_generated_address_group_service_add_address_group_items_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_AddAddressGroupItems_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_add_address_group_items_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", - "shortName": "AddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.add_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.AddAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "AddAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "items", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "add_address_group_items" - }, - "description": "Sample for AddAddressGroupItems", - "file": "networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_AddAddressGroupItems_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", - "shortName": "AddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.clone_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CloneAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "CloneAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "source_address_group", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "clone_address_group_items" - }, - "description": "Sample for CloneAddressGroupItems", - "file": "networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_CloneAddressGroupItems_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", - "shortName": "AddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.clone_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CloneAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "CloneAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "source_address_group", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "clone_address_group_items" - }, - "description": "Sample for CloneAddressGroupItems", - "file": "networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_CloneAddressGroupItems_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", - "shortName": "AddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.create_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CreateAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "CreateAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" - }, - { - "name": "address_group_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_address_group" - }, - "description": "Sample for CreateAddressGroup", - "file": "networksecurity_v1_generated_address_group_service_create_address_group_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_CreateAddressGroup_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_create_address_group_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", - "shortName": "AddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.create_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CreateAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "CreateAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" - }, - { - "name": "address_group_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_address_group" - }, - "description": "Sample for CreateAddressGroup", - "file": "networksecurity_v1_generated_address_group_service_create_address_group_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_CreateAddressGroup_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_create_address_group_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", - "shortName": "AddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.delete_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.DeleteAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "DeleteAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_address_group" - }, - "description": "Sample for DeleteAddressGroup", - "file": "networksecurity_v1_generated_address_group_service_delete_address_group_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_DeleteAddressGroup_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_delete_address_group_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", - "shortName": "AddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.delete_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.DeleteAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "DeleteAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_address_group" - }, - "description": "Sample for DeleteAddressGroup", - "file": "networksecurity_v1_generated_address_group_service_delete_address_group_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_DeleteAddressGroup_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_delete_address_group_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", - "shortName": "AddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.get_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.GetAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "GetAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.types.AddressGroup", - "shortName": "get_address_group" - }, - "description": "Sample for GetAddressGroup", - "file": "networksecurity_v1_generated_address_group_service_get_address_group_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_GetAddressGroup_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_get_address_group_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", - "shortName": "AddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.get_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.GetAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "GetAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.types.AddressGroup", - "shortName": "get_address_group" - }, - "description": "Sample for GetAddressGroup", - "file": "networksecurity_v1_generated_address_group_service_get_address_group_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_GetAddressGroup_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_get_address_group_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", - "shortName": "AddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.list_address_group_references", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroupReferences", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "ListAddressGroupReferences" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupReferencesAsyncPager", - "shortName": "list_address_group_references" - }, - "description": "Sample for ListAddressGroupReferences", - "file": "networksecurity_v1_generated_address_group_service_list_address_group_references_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroupReferences_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_list_address_group_references_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", - "shortName": "AddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.list_address_group_references", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroupReferences", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "ListAddressGroupReferences" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupReferencesPager", - "shortName": "list_address_group_references" - }, - "description": "Sample for ListAddressGroupReferences", - "file": "networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroupReferences_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", - "shortName": "AddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.list_address_groups", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroups", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "ListAddressGroups" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupsAsyncPager", - "shortName": "list_address_groups" - }, - "description": "Sample for ListAddressGroups", - "file": "networksecurity_v1_generated_address_group_service_list_address_groups_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroups_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_list_address_groups_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", - "shortName": "AddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.list_address_groups", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroups", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "ListAddressGroups" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupsPager", - "shortName": "list_address_groups" - }, - "description": "Sample for ListAddressGroups", - "file": "networksecurity_v1_generated_address_group_service_list_address_groups_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroups_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_list_address_groups_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", - "shortName": "AddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.remove_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.RemoveAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "RemoveAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "items", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "remove_address_group_items" - }, - "description": "Sample for RemoveAddressGroupItems", - "file": "networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_RemoveAddressGroupItems_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", - "shortName": "AddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.remove_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.RemoveAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "RemoveAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "items", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "remove_address_group_items" - }, - "description": "Sample for RemoveAddressGroupItems", - "file": "networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_RemoveAddressGroupItems_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", - "shortName": "AddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.update_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.UpdateAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "UpdateAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" - }, - { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_address_group" - }, - "description": "Sample for UpdateAddressGroup", - "file": "networksecurity_v1_generated_address_group_service_update_address_group_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_UpdateAddressGroup_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_update_address_group_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", - "shortName": "AddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.update_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService.UpdateAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.AddressGroupService", - "shortName": "AddressGroupService" - }, - "shortName": "UpdateAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" - }, - { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_address_group" - }, - "description": "Sample for UpdateAddressGroup", - "file": "networksecurity_v1_generated_address_group_service_update_address_group_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_AddressGroupService_UpdateAddressGroup_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_address_group_service_update_address_group_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" - }, - { - "name": "authorization_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_authorization_policy" - }, - "description": "Sample for CreateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" - }, - { - "name": "authorization_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_authorization_policy" - }, - "description": "Sample for CreateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" - }, - { - "name": "client_tls_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_client_tls_policy" - }, - "description": "Sample for CreateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" - }, - { - "name": "client_tls_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_client_tls_policy" - }, - "description": "Sample for CreateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" - }, - { - "name": "server_tls_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_server_tls_policy" - }, - "description": "Sample for CreateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" - }, - { - "name": "server_tls_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_server_tls_policy" - }, - "description": "Sample for CreateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_authorization_policy" - }, - "description": "Sample for DeleteAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_authorization_policy" - }, - "description": "Sample for DeleteAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_client_tls_policy" - }, - "description": "Sample for DeleteClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_client_tls_policy" - }, - "description": "Sample for DeleteClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_server_tls_policy" - }, - "description": "Sample for DeleteServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_server_tls_policy" - }, - "description": "Sample for DeleteServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", - "shortName": "get_authorization_policy" - }, - "description": "Sample for GetAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", - "shortName": "get_authorization_policy" - }, - "description": "Sample for GetAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", - "shortName": "get_client_tls_policy" - }, - "description": "Sample for GetClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", - "shortName": "get_client_tls_policy" - }, - "description": "Sample for GetClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", - "shortName": "get_server_tls_policy" - }, - "description": "Sample for GetServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", - "shortName": "get_server_tls_policy" - }, - "description": "Sample for GetServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_authorization_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListAuthorizationPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager", - "shortName": "list_authorization_policies" - }, - "description": "Sample for ListAuthorizationPolicies", - "file": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_authorization_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListAuthorizationPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesPager", - "shortName": "list_authorization_policies" - }, - "description": "Sample for ListAuthorizationPolicies", - "file": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_client_tls_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListClientTlsPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager", - "shortName": "list_client_tls_policies" - }, - "description": "Sample for ListClientTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_client_tls_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListClientTlsPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesPager", - "shortName": "list_client_tls_policies" - }, - "description": "Sample for ListClientTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_server_tls_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListServerTlsPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager", - "shortName": "list_server_tls_policies" - }, - "description": "Sample for ListServerTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_server_tls_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListServerTlsPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesPager", - "shortName": "list_server_tls_policies" - }, - "description": "Sample for ListServerTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_authorization_policy" - }, - "description": "Sample for UpdateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_authorization_policy" - }, - "description": "Sample for UpdateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_client_tls_policy" - }, - "description": "Sample for UpdateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_client_tls_policy" - }, - "description": "Sample for UpdateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_server_tls_policy" - }, - "description": "Sample for UpdateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_server_tls_policy" - }, - "description": "Sample for UpdateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.add_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.AddAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "AddAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "items", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "add_address_group_items" - }, - "description": "Sample for AddAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.add_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.AddAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "AddAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "items", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "add_address_group_items" - }, - "description": "Sample for AddAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.clone_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CloneAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "CloneAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "source_address_group", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "clone_address_group_items" - }, - "description": "Sample for CloneAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.clone_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CloneAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "CloneAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "source_address_group", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "clone_address_group_items" - }, - "description": "Sample for CloneAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.create_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CreateAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "CreateAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" - }, - { - "name": "address_group_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_address_group" - }, - "description": "Sample for CreateAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.create_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CreateAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "CreateAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" - }, - { - "name": "address_group_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_address_group" - }, - "description": "Sample for CreateAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.delete_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.DeleteAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "DeleteAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_address_group" - }, - "description": "Sample for DeleteAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.delete_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.DeleteAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "DeleteAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_address_group" - }, - "description": "Sample for DeleteAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.get_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.GetAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "GetAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.types.AddressGroup", - "shortName": "get_address_group" - }, - "description": "Sample for GetAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.get_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.GetAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "GetAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.types.AddressGroup", - "shortName": "get_address_group" - }, - "description": "Sample for GetAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.list_address_group_references", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroupReferences", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "ListAddressGroupReferences" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesAsyncPager", - "shortName": "list_address_group_references" - }, - "description": "Sample for ListAddressGroupReferences", - "file": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.list_address_group_references", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroupReferences", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "ListAddressGroupReferences" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesPager", - "shortName": "list_address_group_references" - }, - "description": "Sample for ListAddressGroupReferences", - "file": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.list_address_groups", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroups", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "ListAddressGroups" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsAsyncPager", - "shortName": "list_address_groups" - }, - "description": "Sample for ListAddressGroups", - "file": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.list_address_groups", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroups", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "ListAddressGroups" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsPager", - "shortName": "list_address_groups" - }, - "description": "Sample for ListAddressGroups", - "file": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.remove_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.RemoveAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "RemoveAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "items", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "remove_address_group_items" - }, - "description": "Sample for RemoveAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.remove_address_group_items", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.RemoveAddressGroupItems", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "RemoveAddressGroupItems" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" - }, - { - "name": "address_group", - "type": "str" - }, - { - "name": "items", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "remove_address_group_items" - }, - "description": "Sample for RemoveAddressGroupItems", - "file": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", - "shortName": "OrganizationAddressGroupServiceAsyncClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.update_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.UpdateAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "UpdateAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" - }, - { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_address_group" - }, - "description": "Sample for UpdateAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", - "shortName": "OrganizationAddressGroupServiceClient" - }, - "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.update_address_group", - "method": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.UpdateAddressGroup", - "service": { - "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "shortName": "OrganizationAddressGroupService" - }, - "shortName": "UpdateAddressGroup" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" - }, - { - "name": "address_group", - "type": "google.cloud.network_security_v1.types.AddressGroup" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_address_group" - }, - "description": "Sample for UpdateAddressGroup", - "file": "networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-network-security/v1/scripts/fixup_network_security_v1_keywords.py b/owl-bot-staging/google-cloud-network-security/v1/scripts/fixup_network_security_v1_keywords.py deleted file mode 100644 index 4404e816019e..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/scripts/fixup_network_security_v1_keywords.py +++ /dev/null @@ -1,199 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 network_securityCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'add_address_group_items': ('address_group', 'items', 'request_id', ), - 'clone_address_group_items': ('address_group', 'source_address_group', 'request_id', ), - 'create_address_group': ('parent', 'address_group_id', 'address_group', 'request_id', ), - 'create_authorization_policy': ('parent', 'authorization_policy_id', 'authorization_policy', ), - 'create_client_tls_policy': ('parent', 'client_tls_policy_id', 'client_tls_policy', ), - 'create_server_tls_policy': ('parent', 'server_tls_policy_id', 'server_tls_policy', ), - 'delete_address_group': ('name', 'request_id', ), - 'delete_authorization_policy': ('name', ), - 'delete_client_tls_policy': ('name', ), - 'delete_server_tls_policy': ('name', ), - 'get_address_group': ('name', ), - 'get_authorization_policy': ('name', ), - 'get_client_tls_policy': ('name', ), - 'get_server_tls_policy': ('name', ), - 'list_address_group_references': ('address_group', 'page_size', 'page_token', ), - 'list_address_groups': ('parent', 'page_size', 'page_token', 'return_partial_success', ), - 'list_authorization_policies': ('parent', 'page_size', 'page_token', ), - 'list_client_tls_policies': ('parent', 'page_size', 'page_token', ), - 'list_server_tls_policies': ('parent', 'page_size', 'page_token', ), - 'remove_address_group_items': ('address_group', 'items', 'request_id', ), - 'update_address_group': ('address_group', 'update_mask', 'request_id', ), - 'update_authorization_policy': ('authorization_policy', 'update_mask', ), - 'update_client_tls_policy': ('client_tls_policy', 'update_mask', ), - 'update_server_tls_policy': ('server_tls_policy', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=network_securityCallTransformer(), -): - """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 network_security 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/google-cloud-network-security/v1/setup.py b/owl-bot-staging/google-cloud-network-security/v1/setup.py deleted file mode 100644 index 1f618aa7ad2f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-network-security' - - -description = "Google Cloud Network Security API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/network_security/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0", - "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", - "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.14.0, <1.0.0", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.13.txt deleted file mode 100644 index 2010e549cceb..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,12 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -proto-plus>=1 -protobuf>=6 -grpc-google-iam-v1>=0 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.7.txt deleted file mode 100644 index 56affbd9bd75..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.14.0 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1/tests/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/tests/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_network_security.py b/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_network_security.py deleted file mode 100644 index 6df5103b049b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_network_security.py +++ /dev/null @@ -1,14565 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.location import locations_pb2 -from google.cloud.network_security_v1.services.network_security import NetworkSecurityAsyncClient -from google.cloud.network_security_v1.services.network_security import NetworkSecurityClient -from google.cloud.network_security_v1.services.network_security import pagers -from google.cloud.network_security_v1.services.network_security import transports -from google.cloud.network_security_v1.types import authorization_policy -from google.cloud.network_security_v1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1.types import client_tls_policy -from google.cloud.network_security_v1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1.types import common -from google.cloud.network_security_v1.types import server_tls_policy -from google.cloud.network_security_v1.types import server_tls_policy as gcn_server_tls_policy -from google.cloud.network_security_v1.types import tls -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# 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 - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -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 NetworkSecurityClient._get_default_mtls_endpoint(None) is None - assert NetworkSecurityClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert NetworkSecurityClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - NetworkSecurityClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - NetworkSecurityClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert NetworkSecurityClient._get_client_cert_source(None, False) is None - assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert NetworkSecurityClient._get_client_cert_source(None, True) is mock_default_cert_source - assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE - default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert NetworkSecurityClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - assert NetworkSecurityClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert NetworkSecurityClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert NetworkSecurityClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert NetworkSecurityClient._get_universe_domain(None, None) == NetworkSecurityClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - NetworkSecurityClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) -def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): - cred = mock.Mock(["get_cred_info"]) - cred.get_cred_info = mock.Mock(return_value=cred_info_json) - client = NetworkSecurityClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401,403,404,500]) -def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): - cred = mock.Mock([]) - assert not hasattr(cred, "get_cred_info") - client = NetworkSecurityClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -@pytest.mark.parametrize("client_class,transport_name", [ - (NetworkSecurityClient, "grpc"), - (NetworkSecurityAsyncClient, "grpc_asyncio"), - (NetworkSecurityClient, "rest"), -]) -def test_network_security_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networksecurity.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.NetworkSecurityGrpcTransport, "grpc"), - (transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.NetworkSecurityRestTransport, "rest"), -]) -def test_network_security_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (NetworkSecurityClient, "grpc"), - (NetworkSecurityAsyncClient, "grpc_asyncio"), - (NetworkSecurityClient, "rest"), -]) -def test_network_security_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networksecurity.googleapis.com' - ) - - -def test_network_security_client_get_transport_class(): - transport = NetworkSecurityClient.get_transport_class() - available_transports = [ - transports.NetworkSecurityGrpcTransport, - transports.NetworkSecurityRestTransport, - ] - assert transport in available_transports - - transport = NetworkSecurityClient.get_transport_class("grpc") - assert transport == transports.NetworkSecurityGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), - (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"), -]) -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -def test_network_security_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(NetworkSecurityClient, '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(NetworkSecurityClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "true"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "false"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", "true"), - (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", "false"), -]) -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_network_security_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - NetworkSecurityClient, NetworkSecurityAsyncClient -]) -@mock.patch.object(NetworkSecurityClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityAsyncClient)) -def test_network_security_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - NetworkSecurityClient, NetworkSecurityAsyncClient -]) -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -def test_network_security_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE - default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), - (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"), -]) -def test_network_security_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", None), -]) -def test_network_security_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_network_security_client_client_options_from_dict(): - with mock.patch('google.cloud.network_security_v1.services.network_security.transports.NetworkSecurityGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = NetworkSecurityClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_network_security_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "networksecurity.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="networksecurity.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - authorization_policy.ListAuthorizationPoliciesRequest, - dict, -]) -def test_list_authorization_policies(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_authorization_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = authorization_policy.ListAuthorizationPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizationPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_authorization_policies_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = authorization_policy.ListAuthorizationPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_authorization_policies(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == authorization_policy.ListAuthorizationPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_authorization_policies_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_authorization_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_authorization_policies] = mock_rpc - request = {} - client.list_authorization_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_authorization_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_authorization_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_authorization_policies in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_authorization_policies] = mock_rpc - - request = {} - await client.list_authorization_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_authorization_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_authorization_policies_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.ListAuthorizationPoliciesRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_authorization_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = authorization_policy.ListAuthorizationPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizationPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_authorization_policies_async_from_dict(): - await test_list_authorization_policies_async(request_type=dict) - -def test_list_authorization_policies_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.ListAuthorizationPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() - client.list_authorization_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_authorization_policies_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.ListAuthorizationPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse()) - await client.list_authorization_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_authorization_policies_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_authorization_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_authorization_policies_flattened_error(): - client = NetworkSecurityClient( - 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_authorization_policies( - authorization_policy.ListAuthorizationPoliciesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_authorization_policies_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_authorization_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_authorization_policies_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_authorization_policies( - authorization_policy.ListAuthorizationPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_authorization_policies_pager(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='abc', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[], - next_page_token='def', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='ghi', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_authorization_policies(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, authorization_policy.AuthorizationPolicy) - for i in results) -def test_list_authorization_policies_pages(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='abc', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[], - next_page_token='def', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='ghi', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_authorization_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_list_authorization_policies_async_pager(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='abc', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[], - next_page_token='def', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='ghi', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_authorization_policies(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, authorization_policy.AuthorizationPolicy) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_authorization_policies_async_pages(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='abc', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[], - next_page_token='def', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='ghi', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_authorization_policies(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - authorization_policy.GetAuthorizationPolicyRequest, - dict, -]) -def test_get_authorization_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.AuthorizationPolicy( - name='name_value', - description='description_value', - action=authorization_policy.AuthorizationPolicy.Action.ALLOW, - ) - response = client.get_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = authorization_policy.GetAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, authorization_policy.AuthorizationPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW - - -def test_get_authorization_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = authorization_policy.GetAuthorizationPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_authorization_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == authorization_policy.GetAuthorizationPolicyRequest( - name='name_value', - ) - -def test_get_authorization_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_authorization_policy] = mock_rpc - request = {} - client.get_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_authorization_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_authorization_policy] = mock_rpc - - request = {} - await client.get_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.GetAuthorizationPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy( - name='name_value', - description='description_value', - action=authorization_policy.AuthorizationPolicy.Action.ALLOW, - )) - response = await client.get_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = authorization_policy.GetAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, authorization_policy.AuthorizationPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW - - -@pytest.mark.asyncio -async def test_get_authorization_policy_async_from_dict(): - await test_get_authorization_policy_async(request_type=dict) - -def test_get_authorization_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.GetAuthorizationPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - call.return_value = authorization_policy.AuthorizationPolicy() - client.get_authorization_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_authorization_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.GetAuthorizationPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy()) - await client.get_authorization_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_authorization_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.AuthorizationPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_authorization_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_authorization_policy_flattened_error(): - client = NetworkSecurityClient( - 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_authorization_policy( - authorization_policy.GetAuthorizationPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_authorization_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.AuthorizationPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_authorization_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_authorization_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_authorization_policy( - authorization_policy.GetAuthorizationPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_authorization_policy.CreateAuthorizationPolicyRequest, - dict, -]) -def test_create_authorization_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_authorization_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest( - parent='parent_value', - authorization_policy_id='authorization_policy_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_authorization_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_authorization_policy.CreateAuthorizationPolicyRequest( - parent='parent_value', - authorization_policy_id='authorization_policy_id_value', - ) - -def test_create_authorization_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_authorization_policy] = mock_rpc - request = {} - client.create_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_authorization_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_authorization_policy] = mock_rpc - - request = {} - await client.create_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_authorization_policy_async_from_dict(): - await test_create_authorization_policy_async(request_type=dict) - -def test_create_authorization_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_authorization_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_authorization_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_authorization_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_authorization_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_authorization_policy( - parent='parent_value', - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - authorization_policy_id='authorization_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].authorization_policy - mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') - assert arg == mock_val - arg = args[0].authorization_policy_id - mock_val = 'authorization_policy_id_value' - assert arg == mock_val - - -def test_create_authorization_policy_flattened_error(): - client = NetworkSecurityClient( - 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_authorization_policy( - gcn_authorization_policy.CreateAuthorizationPolicyRequest(), - parent='parent_value', - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - authorization_policy_id='authorization_policy_id_value', - ) - -@pytest.mark.asyncio -async def test_create_authorization_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_authorization_policy( - parent='parent_value', - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - authorization_policy_id='authorization_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].authorization_policy - mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') - assert arg == mock_val - arg = args[0].authorization_policy_id - mock_val = 'authorization_policy_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_authorization_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_authorization_policy( - gcn_authorization_policy.CreateAuthorizationPolicyRequest(), - parent='parent_value', - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - authorization_policy_id='authorization_policy_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_authorization_policy.UpdateAuthorizationPolicyRequest, - dict, -]) -def test_update_authorization_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_authorization_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_authorization_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_authorization_policy.UpdateAuthorizationPolicyRequest( - ) - -def test_update_authorization_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_authorization_policy] = mock_rpc - request = {} - client.update_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_authorization_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_authorization_policy] = mock_rpc - - request = {} - await client.update_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_authorization_policy_async_from_dict(): - await test_update_authorization_policy_async(request_type=dict) - -def test_update_authorization_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - - request.authorization_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_authorization_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', - 'authorization_policy.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_authorization_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - - request.authorization_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_authorization_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', - 'authorization_policy.name=name_value', - ) in kw['metadata'] - - -def test_update_authorization_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_authorization_policy( - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].authorization_policy - mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_authorization_policy_flattened_error(): - client = NetworkSecurityClient( - 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_authorization_policy( - gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_authorization_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_authorization_policy( - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].authorization_policy - mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_authorization_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_authorization_policy( - gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - authorization_policy.DeleteAuthorizationPolicyRequest, - dict, -]) -def test_delete_authorization_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = authorization_policy.DeleteAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_authorization_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = authorization_policy.DeleteAuthorizationPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_authorization_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == authorization_policy.DeleteAuthorizationPolicyRequest( - name='name_value', - ) - -def test_delete_authorization_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_authorization_policy] = mock_rpc - request = {} - client.delete_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_authorization_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_authorization_policy] = mock_rpc - - request = {} - await client.delete_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.DeleteAuthorizationPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = authorization_policy.DeleteAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_authorization_policy_async_from_dict(): - await test_delete_authorization_policy_async(request_type=dict) - -def test_delete_authorization_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.DeleteAuthorizationPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_authorization_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_authorization_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.DeleteAuthorizationPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_authorization_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_authorization_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_authorization_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_authorization_policy_flattened_error(): - client = NetworkSecurityClient( - 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_authorization_policy( - authorization_policy.DeleteAuthorizationPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_authorization_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_authorization_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_authorization_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_authorization_policy( - authorization_policy.DeleteAuthorizationPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - server_tls_policy.ListServerTlsPoliciesRequest, - dict, -]) -def test_list_server_tls_policies(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_server_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = server_tls_policy.ListServerTlsPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServerTlsPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_server_tls_policies_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = server_tls_policy.ListServerTlsPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_server_tls_policies(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == server_tls_policy.ListServerTlsPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_server_tls_policies_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_server_tls_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_server_tls_policies] = mock_rpc - request = {} - client.list_server_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_server_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_server_tls_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_server_tls_policies in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_server_tls_policies] = mock_rpc - - request = {} - await client.list_server_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_server_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_server_tls_policies_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.ListServerTlsPoliciesRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_server_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = server_tls_policy.ListServerTlsPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServerTlsPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_server_tls_policies_async_from_dict(): - await test_list_server_tls_policies_async(request_type=dict) - -def test_list_server_tls_policies_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.ListServerTlsPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() - client.list_server_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_server_tls_policies_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.ListServerTlsPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse()) - await client.list_server_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_server_tls_policies_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_server_tls_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_server_tls_policies_flattened_error(): - client = NetworkSecurityClient( - 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_server_tls_policies( - server_tls_policy.ListServerTlsPoliciesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_server_tls_policies_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_server_tls_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_server_tls_policies_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_server_tls_policies( - server_tls_policy.ListServerTlsPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_server_tls_policies_pager(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='abc', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[], - next_page_token='def', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='ghi', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_server_tls_policies(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) - for i in results) -def test_list_server_tls_policies_pages(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='abc', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[], - next_page_token='def', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='ghi', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_server_tls_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_list_server_tls_policies_async_pager(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='abc', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[], - next_page_token='def', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='ghi', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_server_tls_policies(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_server_tls_policies_async_pages(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='abc', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[], - next_page_token='def', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='ghi', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_server_tls_policies(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - server_tls_policy.GetServerTlsPolicyRequest, - dict, -]) -def test_get_server_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ServerTlsPolicy( - name='name_value', - description='description_value', - allow_open=True, - ) - response = client.get_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = server_tls_policy.GetServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, server_tls_policy.ServerTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.allow_open is True - - -def test_get_server_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = server_tls_policy.GetServerTlsPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_server_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == server_tls_policy.GetServerTlsPolicyRequest( - name='name_value', - ) - -def test_get_server_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_server_tls_policy] = mock_rpc - request = {} - client.get_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_server_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_server_tls_policy] = mock_rpc - - request = {} - await client.get_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.GetServerTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy( - name='name_value', - description='description_value', - allow_open=True, - )) - response = await client.get_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = server_tls_policy.GetServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, server_tls_policy.ServerTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.allow_open is True - - -@pytest.mark.asyncio -async def test_get_server_tls_policy_async_from_dict(): - await test_get_server_tls_policy_async(request_type=dict) - -def test_get_server_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.GetServerTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - call.return_value = server_tls_policy.ServerTlsPolicy() - client.get_server_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_server_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.GetServerTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy()) - await client.get_server_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_server_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ServerTlsPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_server_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_server_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_server_tls_policy( - server_tls_policy.GetServerTlsPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_server_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ServerTlsPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_server_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_server_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_server_tls_policy( - server_tls_policy.GetServerTlsPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_server_tls_policy.CreateServerTlsPolicyRequest, - dict, -]) -def test_create_server_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_server_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest( - parent='parent_value', - server_tls_policy_id='server_tls_policy_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_server_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_server_tls_policy.CreateServerTlsPolicyRequest( - parent='parent_value', - server_tls_policy_id='server_tls_policy_id_value', - ) - -def test_create_server_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_server_tls_policy] = mock_rpc - request = {} - client.create_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_server_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_server_tls_policy] = mock_rpc - - request = {} - await client.create_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_server_tls_policy_async_from_dict(): - await test_create_server_tls_policy_async(request_type=dict) - -def test_create_server_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_server_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_server_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_server_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_server_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_server_tls_policy( - parent='parent_value', - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - server_tls_policy_id='server_tls_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].server_tls_policy - mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].server_tls_policy_id - mock_val = 'server_tls_policy_id_value' - assert arg == mock_val - - -def test_create_server_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_server_tls_policy( - gcn_server_tls_policy.CreateServerTlsPolicyRequest(), - parent='parent_value', - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - server_tls_policy_id='server_tls_policy_id_value', - ) - -@pytest.mark.asyncio -async def test_create_server_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_server_tls_policy( - parent='parent_value', - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - server_tls_policy_id='server_tls_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].server_tls_policy - mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].server_tls_policy_id - mock_val = 'server_tls_policy_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_server_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_server_tls_policy( - gcn_server_tls_policy.CreateServerTlsPolicyRequest(), - parent='parent_value', - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - server_tls_policy_id='server_tls_policy_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_server_tls_policy.UpdateServerTlsPolicyRequest, - dict, -]) -def test_update_server_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_server_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_server_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_server_tls_policy.UpdateServerTlsPolicyRequest( - ) - -def test_update_server_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_server_tls_policy] = mock_rpc - request = {} - client.update_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_server_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_server_tls_policy] = mock_rpc - - request = {} - await client.update_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_server_tls_policy_async_from_dict(): - await test_update_server_tls_policy_async(request_type=dict) - -def test_update_server_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - - request.server_tls_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_server_tls_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', - 'server_tls_policy.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_server_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - - request.server_tls_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_server_tls_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', - 'server_tls_policy.name=name_value', - ) in kw['metadata'] - - -def test_update_server_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_server_tls_policy( - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].server_tls_policy - mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_server_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_server_tls_policy( - gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_server_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_server_tls_policy( - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].server_tls_policy - mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_server_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_server_tls_policy( - gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - server_tls_policy.DeleteServerTlsPolicyRequest, - dict, -]) -def test_delete_server_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = server_tls_policy.DeleteServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_server_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = server_tls_policy.DeleteServerTlsPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_server_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == server_tls_policy.DeleteServerTlsPolicyRequest( - name='name_value', - ) - -def test_delete_server_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_server_tls_policy] = mock_rpc - request = {} - client.delete_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_server_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_server_tls_policy] = mock_rpc - - request = {} - await client.delete_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.DeleteServerTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = server_tls_policy.DeleteServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_async_from_dict(): - await test_delete_server_tls_policy_async(request_type=dict) - -def test_delete_server_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.DeleteServerTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_server_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.DeleteServerTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_server_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_server_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_server_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_server_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_server_tls_policy( - server_tls_policy.DeleteServerTlsPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_server_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_server_tls_policy( - server_tls_policy.DeleteServerTlsPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.ListClientTlsPoliciesRequest, - dict, -]) -def test_list_client_tls_policies(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = client_tls_policy.ListClientTlsPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClientTlsPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_client_tls_policies_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = client_tls_policy.ListClientTlsPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_client_tls_policies(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == client_tls_policy.ListClientTlsPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_client_tls_policies_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_client_tls_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_client_tls_policies] = mock_rpc - request = {} - client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_client_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_client_tls_policies in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_client_tls_policies] = mock_rpc - - request = {} - await client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_client_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.ListClientTlsPoliciesRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = client_tls_policy.ListClientTlsPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClientTlsPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async_from_dict(): - await test_list_client_tls_policies_async(request_type=dict) - -def test_list_client_tls_policies_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.ListClientTlsPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - client.list_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_client_tls_policies_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.ListClientTlsPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) - await client.list_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_client_tls_policies_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_client_tls_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_client_tls_policies_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policies( - client_tls_policy.ListClientTlsPoliciesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_client_tls_policies_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_client_tls_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_client_tls_policies_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_client_tls_policies( - client_tls_policy.ListClientTlsPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_client_tls_policies_pager(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_client_tls_policies(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) - for i in results) -def test_list_client_tls_policies_pages(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_client_tls_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_list_client_tls_policies_async_pager(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_client_tls_policies(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async_pages(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_client_tls_policies(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.GetClientTlsPolicyRequest, - dict, -]) -def test_get_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - ) - response = client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = client_tls_policy.GetClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, client_tls_policy.ClientTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.sni == 'sni_value' - - -def test_get_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = client_tls_policy.GetClientTlsPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == client_tls_policy.GetClientTlsPolicyRequest( - name='name_value', - ) - -def test_get_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_client_tls_policy] = mock_rpc - request = {} - client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_client_tls_policy] = mock_rpc - - request = {} - await client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.GetClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - )) - response = await client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = client_tls_policy.GetClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, client_tls_policy.ClientTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.sni == 'sni_value' - - -@pytest.mark.asyncio -async def test_get_client_tls_policy_async_from_dict(): - await test_get_client_tls_policy_async(request_type=dict) - -def test_get_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.GetClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value = client_tls_policy.ClientTlsPolicy() - client.get_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.GetClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) - await client.get_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ClientTlsPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - client_tls_policy.GetClientTlsPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ClientTlsPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_client_tls_policy( - client_tls_policy.GetClientTlsPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_client_tls_policy.CreateClientTlsPolicyRequest, - dict, -]) -def test_create_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest( - parent='parent_value', - client_tls_policy_id='client_tls_policy_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_client_tls_policy.CreateClientTlsPolicyRequest( - parent='parent_value', - client_tls_policy_id='client_tls_policy_id_value', - ) - -def test_create_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_client_tls_policy] = mock_rpc - request = {} - client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_client_tls_policy] = mock_rpc - - request = {} - await client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_client_tls_policy_async_from_dict(): - await test_create_client_tls_policy_async(request_type=dict) - -def test_create_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_client_tls_policy( - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].client_tls_policy_id - mock_val = 'client_tls_policy_id_value' - assert arg == mock_val - - -def test_create_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - gcn_client_tls_policy.CreateClientTlsPolicyRequest(), - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - -@pytest.mark.asyncio -async def test_create_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_client_tls_policy( - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].client_tls_policy_id - mock_val = 'client_tls_policy_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_client_tls_policy( - gcn_client_tls_policy.CreateClientTlsPolicyRequest(), - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_client_tls_policy.UpdateClientTlsPolicyRequest, - dict, -]) -def test_update_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_client_tls_policy.UpdateClientTlsPolicyRequest( - ) - -def test_update_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_client_tls_policy] = mock_rpc - request = {} - client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_client_tls_policy] = mock_rpc - - request = {} - await client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_client_tls_policy_async_from_dict(): - await test_update_client_tls_policy_async(request_type=dict) - -def test_update_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - request.client_tls_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_client_tls_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', - 'client_tls_policy.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - request.client_tls_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_client_tls_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', - 'client_tls_policy.name=name_value', - ) in kw['metadata'] - - -def test_update_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_client_tls_policy( - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_client_tls_policy( - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_client_tls_policy( - gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.DeleteClientTlsPolicyRequest, - dict, -]) -def test_delete_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = client_tls_policy.DeleteClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = client_tls_policy.DeleteClientTlsPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == client_tls_policy.DeleteClientTlsPolicyRequest( - name='name_value', - ) - -def test_delete_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_client_tls_policy] = mock_rpc - request = {} - client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_client_tls_policy] = mock_rpc - - request = {} - await client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.DeleteClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = client_tls_policy.DeleteClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_async_from_dict(): - await test_delete_client_tls_policy_async(request_type=dict) - -def test_delete_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.DeleteClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.DeleteClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - client_tls_policy.DeleteClientTlsPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_client_tls_policy( - client_tls_policy.DeleteClientTlsPolicyRequest(), - name='name_value', - ) - - -def test_list_authorization_policies_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_authorization_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_authorization_policies] = mock_rpc - - request = {} - client.list_authorization_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_authorization_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_authorization_policies_rest_required_fields(request_type=authorization_policy.ListAuthorizationPoliciesRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_authorization_policies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_authorization_policies._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = authorization_policy.ListAuthorizationPoliciesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = authorization_policy.ListAuthorizationPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_authorization_policies(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_authorization_policies_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_authorization_policies._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_authorization_policies_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = authorization_policy.ListAuthorizationPoliciesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = authorization_policy.ListAuthorizationPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_authorization_policies(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/authorizationPolicies" % client.transport._host, args[1]) - - -def test_list_authorization_policies_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_authorization_policies( - authorization_policy.ListAuthorizationPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_authorization_policies_rest_pager(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='abc', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[], - next_page_token='def', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='ghi', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(authorization_policy.ListAuthorizationPoliciesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_authorization_policies(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, authorization_policy.AuthorizationPolicy) - for i in results) - - pages = list(client.list_authorization_policies(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_authorization_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_authorization_policy] = mock_rpc - - request = {} - client.get_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_authorization_policy_rest_required_fields(request_type=authorization_policy.GetAuthorizationPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_authorization_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_authorization_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = authorization_policy.AuthorizationPolicy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = authorization_policy.AuthorizationPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_authorization_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_authorization_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_authorization_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_authorization_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = authorization_policy.AuthorizationPolicy() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = authorization_policy.AuthorizationPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_authorization_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/authorizationPolicies/*}" % client.transport._host, args[1]) - - -def test_get_authorization_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_authorization_policy( - authorization_policy.GetAuthorizationPolicyRequest(), - name='name_value', - ) - - -def test_create_authorization_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_authorization_policy] = mock_rpc - - request = {} - client.create_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_authorization_policy_rest_required_fields(request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["authorization_policy_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "authorizationPolicyId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_authorization_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "authorizationPolicyId" in jsonified_request - assert jsonified_request["authorizationPolicyId"] == request_init["authorization_policy_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["authorizationPolicyId"] = 'authorization_policy_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_authorization_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("authorization_policy_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "authorizationPolicyId" in jsonified_request - assert jsonified_request["authorizationPolicyId"] == 'authorization_policy_id_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_authorization_policy(request) - - expected_params = [ - ( - "authorizationPolicyId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_authorization_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_authorization_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("authorizationPolicyId", )) & set(("parent", "authorizationPolicyId", "authorizationPolicy", ))) - - -def test_create_authorization_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - authorization_policy_id='authorization_policy_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_authorization_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/authorizationPolicies" % client.transport._host, args[1]) - - -def test_create_authorization_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_authorization_policy( - gcn_authorization_policy.CreateAuthorizationPolicyRequest(), - parent='parent_value', - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - authorization_policy_id='authorization_policy_id_value', - ) - - -def test_update_authorization_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_authorization_policy] = mock_rpc - - request = {} - client.update_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_authorization_policy_rest_required_fields(request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_authorization_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_authorization_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_authorization_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_authorization_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_authorization_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("authorizationPolicy", ))) - - -def test_update_authorization_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'authorization_policy': {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_authorization_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{authorization_policy.name=projects/*/locations/*/authorizationPolicies/*}" % client.transport._host, args[1]) - - -def test_update_authorization_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_authorization_policy( - gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_authorization_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_authorization_policy] = mock_rpc - - request = {} - client.delete_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_authorization_policy_rest_required_fields(request_type=authorization_policy.DeleteAuthorizationPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_authorization_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_authorization_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_authorization_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_authorization_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_authorization_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_authorization_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_authorization_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/authorizationPolicies/*}" % client.transport._host, args[1]) - - -def test_delete_authorization_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_authorization_policy( - authorization_policy.DeleteAuthorizationPolicyRequest(), - name='name_value', - ) - - -def test_list_server_tls_policies_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_server_tls_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_server_tls_policies] = mock_rpc - - request = {} - client.list_server_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_server_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_server_tls_policies_rest_required_fields(request_type=server_tls_policy.ListServerTlsPoliciesRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_server_tls_policies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_server_tls_policies._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = server_tls_policy.ListServerTlsPoliciesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = server_tls_policy.ListServerTlsPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_server_tls_policies(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_server_tls_policies_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_server_tls_policies._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_server_tls_policies_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = server_tls_policy.ListServerTlsPoliciesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = server_tls_policy.ListServerTlsPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_server_tls_policies(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/serverTlsPolicies" % client.transport._host, args[1]) - - -def test_list_server_tls_policies_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_server_tls_policies( - server_tls_policy.ListServerTlsPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_server_tls_policies_rest_pager(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='abc', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[], - next_page_token='def', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='ghi', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(server_tls_policy.ListServerTlsPoliciesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_server_tls_policies(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) - for i in results) - - pages = list(client.list_server_tls_policies(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_server_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_server_tls_policy] = mock_rpc - - request = {} - client.get_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_server_tls_policy_rest_required_fields(request_type=server_tls_policy.GetServerTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_server_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_server_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = server_tls_policy.ServerTlsPolicy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = server_tls_policy.ServerTlsPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_server_tls_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_server_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_server_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_server_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = server_tls_policy.ServerTlsPolicy() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = server_tls_policy.ServerTlsPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_server_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/serverTlsPolicies/*}" % client.transport._host, args[1]) - - -def test_get_server_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_server_tls_policy( - server_tls_policy.GetServerTlsPolicyRequest(), - name='name_value', - ) - - -def test_create_server_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_server_tls_policy] = mock_rpc - - request = {} - client.create_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_server_tls_policy_rest_required_fields(request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["server_tls_policy_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "serverTlsPolicyId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_server_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "serverTlsPolicyId" in jsonified_request - assert jsonified_request["serverTlsPolicyId"] == request_init["server_tls_policy_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["serverTlsPolicyId"] = 'server_tls_policy_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_server_tls_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("server_tls_policy_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "serverTlsPolicyId" in jsonified_request - assert jsonified_request["serverTlsPolicyId"] == 'server_tls_policy_id_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_server_tls_policy(request) - - expected_params = [ - ( - "serverTlsPolicyId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_server_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_server_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("serverTlsPolicyId", )) & set(("parent", "serverTlsPolicyId", "serverTlsPolicy", ))) - - -def test_create_server_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - server_tls_policy_id='server_tls_policy_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_server_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/serverTlsPolicies" % client.transport._host, args[1]) - - -def test_create_server_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_server_tls_policy( - gcn_server_tls_policy.CreateServerTlsPolicyRequest(), - parent='parent_value', - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - server_tls_policy_id='server_tls_policy_id_value', - ) - - -def test_update_server_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_server_tls_policy] = mock_rpc - - request = {} - client.update_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_server_tls_policy_rest_required_fields(request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_server_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_server_tls_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_server_tls_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_server_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_server_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("serverTlsPolicy", ))) - - -def test_update_server_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'server_tls_policy': {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_server_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{server_tls_policy.name=projects/*/locations/*/serverTlsPolicies/*}" % client.transport._host, args[1]) - - -def test_update_server_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_server_tls_policy( - gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_server_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_server_tls_policy] = mock_rpc - - request = {} - client.delete_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_server_tls_policy_rest_required_fields(request_type=server_tls_policy.DeleteServerTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_server_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_server_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_server_tls_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_server_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_server_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_server_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_server_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/serverTlsPolicies/*}" % client.transport._host, args[1]) - - -def test_delete_server_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_server_tls_policy( - server_tls_policy.DeleteServerTlsPolicyRequest(), - name='name_value', - ) - - -def test_list_client_tls_policies_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_client_tls_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_client_tls_policies] = mock_rpc - - request = {} - client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_client_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_client_tls_policies_rest_required_fields(request_type=client_tls_policy.ListClientTlsPoliciesRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_client_tls_policies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_client_tls_policies._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ListClientTlsPoliciesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_client_tls_policies(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_client_tls_policies_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_client_tls_policies._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_client_tls_policies_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ListClientTlsPoliciesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_client_tls_policies(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/clientTlsPolicies" % client.transport._host, args[1]) - - -def test_list_client_tls_policies_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_client_tls_policies( - client_tls_policy.ListClientTlsPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_client_tls_policies_rest_pager(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(client_tls_policy.ListClientTlsPoliciesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_client_tls_policies(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) - for i in results) - - pages = list(client.list_client_tls_policies(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_client_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_client_tls_policy] = mock_rpc - - request = {} - client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_client_tls_policy_rest_required_fields(request_type=client_tls_policy.GetClientTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ClientTlsPolicy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_client_tls_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_client_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_client_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_client_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ClientTlsPolicy() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_client_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) - - -def test_get_client_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_client_tls_policy( - client_tls_policy.GetClientTlsPolicyRequest(), - name='name_value', - ) - - -def test_create_client_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_client_tls_policy] = mock_rpc - - request = {} - client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_client_tls_policy_rest_required_fields(request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["client_tls_policy_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "clientTlsPolicyId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "clientTlsPolicyId" in jsonified_request - assert jsonified_request["clientTlsPolicyId"] == request_init["client_tls_policy_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["clientTlsPolicyId"] = 'client_tls_policy_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_client_tls_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("client_tls_policy_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "clientTlsPolicyId" in jsonified_request - assert jsonified_request["clientTlsPolicyId"] == 'client_tls_policy_id_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_client_tls_policy(request) - - expected_params = [ - ( - "clientTlsPolicyId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_client_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_client_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("clientTlsPolicyId", )) & set(("parent", "clientTlsPolicyId", "clientTlsPolicy", ))) - - -def test_create_client_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_client_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/clientTlsPolicies" % client.transport._host, args[1]) - - -def test_create_client_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_client_tls_policy( - gcn_client_tls_policy.CreateClientTlsPolicyRequest(), - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - -def test_update_client_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_client_tls_policy] = mock_rpc - - request = {} - client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_client_tls_policy_rest_required_fields(request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_client_tls_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_client_tls_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_client_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_client_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("clientTlsPolicy", ))) - - -def test_update_client_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_client_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) - - -def test_update_client_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_client_tls_policy( - gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_client_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_client_tls_policy] = mock_rpc - - request = {} - client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_client_tls_policy_rest_required_fields(request_type=client_tls_policy.DeleteClientTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_client_tls_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_client_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_client_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_client_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_client_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) - - -def test_delete_client_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_client_tls_policy( - client_tls_policy.DeleteClientTlsPolicyRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = NetworkSecurityClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.NetworkSecurityGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.NetworkSecurityGrpcTransport, - transports.NetworkSecurityGrpcAsyncIOTransport, - transports.NetworkSecurityRestTransport, -]) -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_kind_grpc(): - transport = NetworkSecurityClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_authorization_policies_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() - client.list_authorization_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.ListAuthorizationPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_authorization_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - call.return_value = authorization_policy.AuthorizationPolicy() - client.get_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.GetAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_authorization_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_authorization_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_authorization_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_server_tls_policies_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() - client.list_server_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.ListServerTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_server_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - call.return_value = server_tls_policy.ServerTlsPolicy() - client.get_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.GetServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_server_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_server_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_server_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_client_tls_policies_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - client.list_client_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.ListClientTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value = client_tls_policy.ClientTlsPolicy() - client.get_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.GetClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = NetworkSecurityAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_authorization_policies_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse( - next_page_token='next_page_token_value', - )) - await client.list_authorization_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.ListAuthorizationPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy( - name='name_value', - description='description_value', - action=authorization_policy.AuthorizationPolicy.Action.ALLOW, - )) - await client.get_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.GetAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_server_tls_policies_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse( - next_page_token='next_page_token_value', - )) - await client.list_server_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.ListServerTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy( - name='name_value', - description='description_value', - allow_open=True, - )) - await client.get_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.GetServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_client_tls_policies_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - )) - await client.list_client_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.ListClientTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - )) - await client.get_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.GetClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = NetworkSecurityClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_authorization_policies_rest_bad_request(request_type=authorization_policy.ListAuthorizationPoliciesRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_authorization_policies(request) - - -@pytest.mark.parametrize("request_type", [ - authorization_policy.ListAuthorizationPoliciesRequest, - dict, -]) -def test_list_authorization_policies_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = authorization_policy.ListAuthorizationPoliciesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = authorization_policy.ListAuthorizationPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_authorization_policies(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizationPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_authorization_policies_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_authorization_policies") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_authorization_policies_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_list_authorization_policies") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = authorization_policy.ListAuthorizationPoliciesRequest.pb(authorization_policy.ListAuthorizationPoliciesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = authorization_policy.ListAuthorizationPoliciesResponse.to_json(authorization_policy.ListAuthorizationPoliciesResponse()) - req.return_value.content = return_value - - request = authorization_policy.ListAuthorizationPoliciesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = authorization_policy.ListAuthorizationPoliciesResponse() - post_with_metadata.return_value = authorization_policy.ListAuthorizationPoliciesResponse(), metadata - - client.list_authorization_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_authorization_policy_rest_bad_request(request_type=authorization_policy.GetAuthorizationPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_authorization_policy(request) - - -@pytest.mark.parametrize("request_type", [ - authorization_policy.GetAuthorizationPolicyRequest, - dict, -]) -def test_get_authorization_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = authorization_policy.AuthorizationPolicy( - name='name_value', - description='description_value', - action=authorization_policy.AuthorizationPolicy.Action.ALLOW, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = authorization_policy.AuthorizationPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_authorization_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, authorization_policy.AuthorizationPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_authorization_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_authorization_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_authorization_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_get_authorization_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = authorization_policy.GetAuthorizationPolicyRequest.pb(authorization_policy.GetAuthorizationPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = authorization_policy.AuthorizationPolicy.to_json(authorization_policy.AuthorizationPolicy()) - req.return_value.content = return_value - - request = authorization_policy.GetAuthorizationPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = authorization_policy.AuthorizationPolicy() - post_with_metadata.return_value = authorization_policy.AuthorizationPolicy(), metadata - - client.get_authorization_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_authorization_policy_rest_bad_request(request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_authorization_policy(request) - - -@pytest.mark.parametrize("request_type", [ - gcn_authorization_policy.CreateAuthorizationPolicyRequest, - dict, -]) -def test_create_authorization_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["authorization_policy"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'action': 1, 'rules': [{'sources': [{'principals': ['principals_value1', 'principals_value2'], 'ip_blocks': ['ip_blocks_value1', 'ip_blocks_value2']}], 'destinations': [{'hosts': ['hosts_value1', 'hosts_value2'], 'ports': [569, 570], 'methods': ['methods_value1', 'methods_value2'], 'http_header_match': {'regex_match': 'regex_match_value', 'header_name': 'header_name_value'}}]}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gcn_authorization_policy.CreateAuthorizationPolicyRequest.meta.fields["authorization_policy"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["authorization_policy"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["authorization_policy"][field])): - del request_init["authorization_policy"][field][i][subfield] - else: - del request_init["authorization_policy"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_authorization_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_authorization_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_authorization_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_authorization_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_create_authorization_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gcn_authorization_policy.CreateAuthorizationPolicyRequest.pb(gcn_authorization_policy.CreateAuthorizationPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.create_authorization_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_authorization_policy_rest_bad_request(request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'authorization_policy': {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_authorization_policy(request) - - -@pytest.mark.parametrize("request_type", [ - gcn_authorization_policy.UpdateAuthorizationPolicyRequest, - dict, -]) -def test_update_authorization_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'authorization_policy': {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}} - request_init["authorization_policy"] = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'action': 1, 'rules': [{'sources': [{'principals': ['principals_value1', 'principals_value2'], 'ip_blocks': ['ip_blocks_value1', 'ip_blocks_value2']}], 'destinations': [{'hosts': ['hosts_value1', 'hosts_value2'], 'ports': [569, 570], 'methods': ['methods_value1', 'methods_value2'], 'http_header_match': {'regex_match': 'regex_match_value', 'header_name': 'header_name_value'}}]}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.meta.fields["authorization_policy"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["authorization_policy"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["authorization_policy"][field])): - del request_init["authorization_policy"][field][i][subfield] - else: - del request_init["authorization_policy"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_authorization_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_authorization_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_authorization_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_authorization_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_update_authorization_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gcn_authorization_policy.UpdateAuthorizationPolicyRequest.pb(gcn_authorization_policy.UpdateAuthorizationPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.update_authorization_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_authorization_policy_rest_bad_request(request_type=authorization_policy.DeleteAuthorizationPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_authorization_policy(request) - - -@pytest.mark.parametrize("request_type", [ - authorization_policy.DeleteAuthorizationPolicyRequest, - dict, -]) -def test_delete_authorization_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_authorization_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_authorization_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_authorization_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_authorization_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_delete_authorization_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = authorization_policy.DeleteAuthorizationPolicyRequest.pb(authorization_policy.DeleteAuthorizationPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = authorization_policy.DeleteAuthorizationPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.delete_authorization_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_server_tls_policies_rest_bad_request(request_type=server_tls_policy.ListServerTlsPoliciesRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_server_tls_policies(request) - - -@pytest.mark.parametrize("request_type", [ - server_tls_policy.ListServerTlsPoliciesRequest, - dict, -]) -def test_list_server_tls_policies_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = server_tls_policy.ListServerTlsPoliciesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = server_tls_policy.ListServerTlsPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_server_tls_policies(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServerTlsPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_server_tls_policies_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_server_tls_policies") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_server_tls_policies_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_list_server_tls_policies") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = server_tls_policy.ListServerTlsPoliciesRequest.pb(server_tls_policy.ListServerTlsPoliciesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = server_tls_policy.ListServerTlsPoliciesResponse.to_json(server_tls_policy.ListServerTlsPoliciesResponse()) - req.return_value.content = return_value - - request = server_tls_policy.ListServerTlsPoliciesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = server_tls_policy.ListServerTlsPoliciesResponse() - post_with_metadata.return_value = server_tls_policy.ListServerTlsPoliciesResponse(), metadata - - client.list_server_tls_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_server_tls_policy_rest_bad_request(request_type=server_tls_policy.GetServerTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_server_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - server_tls_policy.GetServerTlsPolicyRequest, - dict, -]) -def test_get_server_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = server_tls_policy.ServerTlsPolicy( - name='name_value', - description='description_value', - allow_open=True, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = server_tls_policy.ServerTlsPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_server_tls_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, server_tls_policy.ServerTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.allow_open is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_server_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_server_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_server_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_get_server_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = server_tls_policy.GetServerTlsPolicyRequest.pb(server_tls_policy.GetServerTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = server_tls_policy.ServerTlsPolicy.to_json(server_tls_policy.ServerTlsPolicy()) - req.return_value.content = return_value - - request = server_tls_policy.GetServerTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = server_tls_policy.ServerTlsPolicy() - post_with_metadata.return_value = server_tls_policy.ServerTlsPolicy(), metadata - - client.get_server_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_server_tls_policy_rest_bad_request(request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_server_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - gcn_server_tls_policy.CreateServerTlsPolicyRequest, - dict, -]) -def test_create_server_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["server_tls_policy"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'allow_open': True, 'server_certificate': {'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'mtls_policy': {'client_validation_ca': [{'grpc_endpoint': {}, 'certificate_provider_instance': {}}]}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gcn_server_tls_policy.CreateServerTlsPolicyRequest.meta.fields["server_tls_policy"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["server_tls_policy"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["server_tls_policy"][field])): - del request_init["server_tls_policy"][field][i][subfield] - else: - del request_init["server_tls_policy"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_server_tls_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_server_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_server_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_server_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_create_server_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gcn_server_tls_policy.CreateServerTlsPolicyRequest.pb(gcn_server_tls_policy.CreateServerTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.create_server_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_server_tls_policy_rest_bad_request(request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'server_tls_policy': {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_server_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - gcn_server_tls_policy.UpdateServerTlsPolicyRequest, - dict, -]) -def test_update_server_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'server_tls_policy': {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'}} - request_init["server_tls_policy"] = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'allow_open': True, 'server_certificate': {'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'mtls_policy': {'client_validation_ca': [{'grpc_endpoint': {}, 'certificate_provider_instance': {}}]}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.meta.fields["server_tls_policy"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["server_tls_policy"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["server_tls_policy"][field])): - del request_init["server_tls_policy"][field][i][subfield] - else: - del request_init["server_tls_policy"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_server_tls_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_server_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_server_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_server_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_update_server_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gcn_server_tls_policy.UpdateServerTlsPolicyRequest.pb(gcn_server_tls_policy.UpdateServerTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.update_server_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_server_tls_policy_rest_bad_request(request_type=server_tls_policy.DeleteServerTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_server_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - server_tls_policy.DeleteServerTlsPolicyRequest, - dict, -]) -def test_delete_server_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/serverTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_server_tls_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_server_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_server_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_server_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_delete_server_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = server_tls_policy.DeleteServerTlsPolicyRequest.pb(server_tls_policy.DeleteServerTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = server_tls_policy.DeleteServerTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.delete_server_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_client_tls_policies_rest_bad_request(request_type=client_tls_policy.ListClientTlsPoliciesRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_client_tls_policies(request) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.ListClientTlsPoliciesRequest, - dict, -]) -def test_list_client_tls_policies_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_client_tls_policies(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClientTlsPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_client_tls_policies_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_client_tls_policies") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_client_tls_policies_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_list_client_tls_policies") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = client_tls_policy.ListClientTlsPoliciesRequest.pb(client_tls_policy.ListClientTlsPoliciesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = client_tls_policy.ListClientTlsPoliciesResponse.to_json(client_tls_policy.ListClientTlsPoliciesResponse()) - req.return_value.content = return_value - - request = client_tls_policy.ListClientTlsPoliciesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - post_with_metadata.return_value = client_tls_policy.ListClientTlsPoliciesResponse(), metadata - - client.list_client_tls_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_client_tls_policy_rest_bad_request(request_type=client_tls_policy.GetClientTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_client_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.GetClientTlsPolicyRequest, - dict, -]) -def test_get_client_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_client_tls_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, client_tls_policy.ClientTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.sni == 'sni_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_client_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_client_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_client_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_get_client_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = client_tls_policy.GetClientTlsPolicyRequest.pb(client_tls_policy.GetClientTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = client_tls_policy.ClientTlsPolicy.to_json(client_tls_policy.ClientTlsPolicy()) - req.return_value.content = return_value - - request = client_tls_policy.GetClientTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = client_tls_policy.ClientTlsPolicy() - post_with_metadata.return_value = client_tls_policy.ClientTlsPolicy(), metadata - - client.get_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_client_tls_policy_rest_bad_request(request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_client_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - gcn_client_tls_policy.CreateClientTlsPolicyRequest, - dict, -]) -def test_create_client_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["client_tls_policy"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'sni': 'sni_value', 'client_certificate': {'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'server_validation_ca': [{'grpc_endpoint': {}, 'certificate_provider_instance': {}}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gcn_client_tls_policy.CreateClientTlsPolicyRequest.meta.fields["client_tls_policy"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["client_tls_policy"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["client_tls_policy"][field])): - del request_init["client_tls_policy"][field][i][subfield] - else: - del request_init["client_tls_policy"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_client_tls_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_client_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_client_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_client_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_create_client_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(gcn_client_tls_policy.CreateClientTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.create_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_client_tls_policy_rest_bad_request(request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_client_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - gcn_client_tls_policy.UpdateClientTlsPolicyRequest, - dict, -]) -def test_update_client_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} - request_init["client_tls_policy"] = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'sni': 'sni_value', 'client_certificate': {'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'server_validation_ca': [{'grpc_endpoint': {}, 'certificate_provider_instance': {}}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.meta.fields["client_tls_policy"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["client_tls_policy"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["client_tls_policy"][field])): - del request_init["client_tls_policy"][field][i][subfield] - else: - del request_init["client_tls_policy"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_client_tls_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_client_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_client_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_client_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_update_client_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(gcn_client_tls_policy.UpdateClientTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.update_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_client_tls_policy_rest_bad_request(request_type=client_tls_policy.DeleteClientTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_client_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.DeleteClientTlsPolicyRequest, - dict, -]) -def test_delete_client_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_client_tls_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_client_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_client_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_client_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_delete_client_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = client_tls_policy.DeleteClientTlsPolicyRequest.pb(client_tls_policy.DeleteClientTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = client_tls_policy.DeleteClientTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.delete_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_initialize_client_w_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_authorization_policies_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - client.list_authorization_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.ListAuthorizationPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_authorization_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - client.get_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.GetAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_authorization_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - client.create_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_authorization_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - client.update_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_authorization_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - client.delete_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_server_tls_policies_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - client.list_server_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.ListServerTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_server_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - client.get_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.GetServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_server_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - client.create_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_server_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - client.update_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_server_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - client.delete_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_client_tls_policies_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - client.list_client_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.ListClientTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_client_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - client.get_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.GetClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_client_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - client.create_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_client_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - client.update_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_client_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - client.delete_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() - - assert args[0] == request_msg - - -def test_network_security_rest_lro_client(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have an api-core operations client. - assert isinstance( - transport.operations_client, -operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.NetworkSecurityGrpcTransport, - ) - -def test_network_security_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.NetworkSecurityTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_network_security_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.network_security_v1.services.network_security.transports.NetworkSecurityTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.NetworkSecurityTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_authorization_policies', - 'get_authorization_policy', - 'create_authorization_policy', - 'update_authorization_policy', - 'delete_authorization_policy', - 'list_server_tls_policies', - 'get_server_tls_policy', - 'create_server_tls_policy', - 'update_server_tls_policy', - 'delete_server_tls_policy', - 'list_client_tls_policies', - 'get_client_tls_policy', - 'create_client_tls_policy', - 'update_client_tls_policy', - 'delete_client_tls_policy', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_network_security_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.network_security_v1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.NetworkSecurityTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_network_security_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.network_security_v1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.NetworkSecurityTransport() - adc.assert_called_once() - - -def test_network_security_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) - NetworkSecurityClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.NetworkSecurityGrpcTransport, - transports.NetworkSecurityGrpcAsyncIOTransport, - ], -) -def test_network_security_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.NetworkSecurityGrpcTransport, - transports.NetworkSecurityGrpcAsyncIOTransport, - transports.NetworkSecurityRestTransport, - ], -) -def test_network_security_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.NetworkSecurityGrpcTransport, grpc_helpers), - (transports.NetworkSecurityGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_network_security_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( - "networksecurity.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="networksecurity.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) -def test_network_security_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_network_security_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.NetworkSecurityRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_network_security_host_no_port(transport_name): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networksecurity.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_network_security_host_with_port(transport_name): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networksecurity.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networksecurity.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_network_security_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = NetworkSecurityClient( - credentials=creds1, - transport=transport_name, - ) - client2 = NetworkSecurityClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_authorization_policies._session - session2 = client2.transport.list_authorization_policies._session - assert session1 != session2 - session1 = client1.transport.get_authorization_policy._session - session2 = client2.transport.get_authorization_policy._session - assert session1 != session2 - session1 = client1.transport.create_authorization_policy._session - session2 = client2.transport.create_authorization_policy._session - assert session1 != session2 - session1 = client1.transport.update_authorization_policy._session - session2 = client2.transport.update_authorization_policy._session - assert session1 != session2 - session1 = client1.transport.delete_authorization_policy._session - session2 = client2.transport.delete_authorization_policy._session - assert session1 != session2 - session1 = client1.transport.list_server_tls_policies._session - session2 = client2.transport.list_server_tls_policies._session - assert session1 != session2 - session1 = client1.transport.get_server_tls_policy._session - session2 = client2.transport.get_server_tls_policy._session - assert session1 != session2 - session1 = client1.transport.create_server_tls_policy._session - session2 = client2.transport.create_server_tls_policy._session - assert session1 != session2 - session1 = client1.transport.update_server_tls_policy._session - session2 = client2.transport.update_server_tls_policy._session - assert session1 != session2 - session1 = client1.transport.delete_server_tls_policy._session - session2 = client2.transport.delete_server_tls_policy._session - assert session1 != session2 - session1 = client1.transport.list_client_tls_policies._session - session2 = client2.transport.list_client_tls_policies._session - assert session1 != session2 - session1 = client1.transport.get_client_tls_policy._session - session2 = client2.transport.get_client_tls_policy._session - assert session1 != session2 - session1 = client1.transport.create_client_tls_policy._session - session2 = client2.transport.create_client_tls_policy._session - assert session1 != session2 - session1 = client1.transport.update_client_tls_policy._session - session2 = client2.transport.update_client_tls_policy._session - assert session1 != session2 - session1 = client1.transport.delete_client_tls_policy._session - session2 = client2.transport.delete_client_tls_policy._session - assert session1 != session2 -def test_network_security_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.NetworkSecurityGrpcTransport( - 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_network_security_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.NetworkSecurityGrpcAsyncIOTransport( - 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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) -def test_network_security_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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) -def test_network_security_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_network_security_grpc_lro_client(): - client = NetworkSecurityClient( - 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_network_security_grpc_lro_async_client(): - client = NetworkSecurityAsyncClient( - 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_authorization_policy_path(): - project = "squid" - location = "clam" - authorization_policy = "whelk" - expected = "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format(project=project, location=location, authorization_policy=authorization_policy, ) - actual = NetworkSecurityClient.authorization_policy_path(project, location, authorization_policy) - assert expected == actual - - -def test_parse_authorization_policy_path(): - expected = { - "project": "octopus", - "location": "oyster", - "authorization_policy": "nudibranch", - } - path = NetworkSecurityClient.authorization_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_authorization_policy_path(path) - assert expected == actual - -def test_client_tls_policy_path(): - project = "cuttlefish" - location = "mussel" - client_tls_policy = "winkle" - expected = "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) - actual = NetworkSecurityClient.client_tls_policy_path(project, location, client_tls_policy) - assert expected == actual - - -def test_parse_client_tls_policy_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "client_tls_policy": "abalone", - } - path = NetworkSecurityClient.client_tls_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_client_tls_policy_path(path) - assert expected == actual - -def test_server_tls_policy_path(): - project = "squid" - location = "clam" - server_tls_policy = "whelk" - expected = "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format(project=project, location=location, server_tls_policy=server_tls_policy, ) - actual = NetworkSecurityClient.server_tls_policy_path(project, location, server_tls_policy) - assert expected == actual - - -def test_parse_server_tls_policy_path(): - expected = { - "project": "octopus", - "location": "oyster", - "server_tls_policy": "nudibranch", - } - path = NetworkSecurityClient.server_tls_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_server_tls_policy_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = NetworkSecurityClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = NetworkSecurityClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = NetworkSecurityClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = NetworkSecurityClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = NetworkSecurityClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = NetworkSecurityClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = NetworkSecurityClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = NetworkSecurityClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = NetworkSecurityClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = NetworkSecurityClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: - transport_class = NetworkSecurityClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_delete_operation(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None - - client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_delete_operation_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_delete_operation_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/.coveragerc b/owl-bot-staging/google-cloud-network-security/v1alpha1/.coveragerc deleted file mode 100644 index ed01d62f0f9a..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/network_security/__init__.py - google/cloud/network_security/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/.flake8 b/owl-bot-staging/google-cloud-network-security/v1alpha1/.flake8 deleted file mode 100644 index 90316de21489..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/.flake8 +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -[flake8] -# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): -# Resolve flake8 lint issues -ignore = E203, E231, E266, E501, W503 -exclude = - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): - # Ensure that generated code passes flake8 lint - **/gapic/** - **/services/** - **/types/** - # Exclude Protobuf gencode - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/LICENSE b/owl-bot-staging/google-cloud-network-security/v1alpha1/LICENSE deleted file mode 100644 index d64569567334..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/google-cloud-network-security/v1alpha1/MANIFEST.in b/owl-bot-staging/google-cloud-network-security/v1alpha1/MANIFEST.in deleted file mode 100644 index dae249ec8976..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/MANIFEST.in +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -include README.rst LICENSE -recursive-include google *.py *.pyi *.json *.proto py.typed -recursive-include tests * -global-exclude *.py[co] -global-exclude __pycache__ diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/README.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/README.rst deleted file mode 100644 index fed4f0a4d3c6..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Cloud Network Security 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 Network Security 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 - - -Logging -------- - -This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. -Note the following: - -#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. -#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. -#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. - - -Simple, environment-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google -logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged -messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging -event. - -A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. - -- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. -- Invalid logging scopes: :code:`foo`, :code:`123`, etc. - -**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. - - -Examples -^^^^^^^^ - -- Enabling the default handler for all Google-based loggers - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google - -- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 - - -Advanced, code-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can also configure a valid logging scope using Python's standard `logging` mechanism. - - -Examples -^^^^^^^^ - -- Configuring a handler for all Google-based loggers - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - -- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google.cloud.library_v1") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - - -Logging details -~~~~~~~~~~~~~~~ - -#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root - logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set - :code:`logging.getLogger("google").propagate = True` in your code. -#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for - one library, but decide you need to also set up environment-based logging configuration for another library. - - #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual - if the code -based configuration gets applied first. - -#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get - executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. - (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_static/custom.css deleted file mode 100644 index b0a295464b23..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_static/custom.css +++ /dev/null @@ -1,20 +0,0 @@ -div#python2-eol { - border-color: red; - border-width: medium; -} - -/* Ensure minimum width for 'Parameters' / 'Returns' column */ -dl.field-list > dt { - min-width: 100px -} - -/* Insert space between methods for readability */ -dl.method { - padding-top: 10px; - padding-bottom: 10px -} - -/* Insert empty space between classes */ -dl.class { - padding-bottom: 50px -} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_templates/layout.html b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_templates/layout.html deleted file mode 100644 index 95e9c77fcfe1..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/_templates/layout.html +++ /dev/null @@ -1,50 +0,0 @@ - -{% extends "!layout.html" %} -{%- block content %} -{%- if theme_fixed_sidebar|lower == 'true' %} -
- {{ sidebar() }} - {%- block document %} -
- {%- if render_sidebar %} -
- {%- endif %} - - {%- block relbar_top %} - {%- if theme_show_relbar_top|tobool %} - - {%- endif %} - {% endblock %} - -
-
- As of January 1, 2020 this library no longer supports Python 2 on the latest released version. - Library versions released prior to that date will continue to be available. For more information please - visit Python 2 support on Google Cloud. -
- {% block body %} {% endblock %} -
- - {%- block relbar_bottom %} - {%- if theme_show_relbar_bottom|tobool %} - - {%- endif %} - {% endblock %} - - {%- if render_sidebar %} -
- {%- endif %} -
- {%- endblock %} -
-
-{%- else %} -{{ super() }} -{%- endif %} -{%- endblock %} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/conf.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/conf.py deleted file mode 100644 index cf26b0443b74..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/conf.py +++ /dev/null @@ -1,385 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-network-security 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("..")) - -# For plugins that can not read conf.py. -# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 -sys.path.insert(0, os.path.abspath(".")) - -__version__ = "" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.5.0" - -# 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.doctest", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", - "recommonmark", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_options = {"members": True} -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# source_suffix = ['.rst', '.md'] -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-network-security" -copyright = u"2025, Google, LLC" -author = u"Google APIs" - -# 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", - "**/.nox/**/*", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/README.rst", -] - -# 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 google-cloud-network-security", - "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-network-security-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-network-security.tex", - u"google-cloud-network-security Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-network-security", - "google-cloud-network-security Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-network-security", - "google-cloud-network-security Documentation", - author, - "google-cloud-network-security", - "google-cloud-network-security Library", - "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": ("https://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), - "google.api_core": ( - "https://googleapis.dev/python/google-api-core/latest/", - None, - ), - "grpc": ("https://grpc.github.io/grpc/python/", None), - "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", 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/google-cloud-network-security/v1alpha1/docs/index.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/index.rst deleted file mode 100644 index 375cdc60fc09..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. include:: multiprocessing.rst - - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - network_security_v1alpha1/services_ - network_security_v1alpha1/types_ diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/multiprocessing.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/multiprocessing.rst deleted file mode 100644 index 536d17b2ea65..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/multiprocessing.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. note:: - - Because this client uses :mod:`grpc` library, it is safe to - share instances across threads. In multiprocessing scenarios, the best - practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.pool.Pool` or - :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/network_security.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/network_security.rst deleted file mode 100644 index 2d5c286998bb..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/network_security.rst +++ /dev/null @@ -1,10 +0,0 @@ -NetworkSecurity ---------------------------------- - -.. automodule:: google.cloud.network_security_v1alpha1.services.network_security - :members: - :inherited-members: - -.. automodule:: google.cloud.network_security_v1alpha1.services.network_security.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/services_.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/services_.rst deleted file mode 100644 index c516f66fcc1b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Network Security v1alpha1 API -======================================================= -.. toctree:: - :maxdepth: 2 - - network_security diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/types_.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/types_.rst deleted file mode 100644 index acd342bb784d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/docs/network_security_v1alpha1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Network Security v1alpha1 API -==================================================== - -.. automodule:: google.cloud.network_security_v1alpha1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/__init__.py deleted file mode 100644 index 583572715ec7..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/__init__.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.network_security import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.network_security_v1alpha1.services.network_security.client import NetworkSecurityClient -from google.cloud.network_security_v1alpha1.services.network_security.async_client import NetworkSecurityAsyncClient - -from google.cloud.network_security_v1alpha1.types.client_tls_policy import ClientTlsPolicy -from google.cloud.network_security_v1alpha1.types.client_tls_policy import CreateClientTlsPolicyRequest -from google.cloud.network_security_v1alpha1.types.client_tls_policy import DeleteClientTlsPolicyRequest -from google.cloud.network_security_v1alpha1.types.client_tls_policy import GetClientTlsPolicyRequest -from google.cloud.network_security_v1alpha1.types.client_tls_policy import ListClientTlsPoliciesRequest -from google.cloud.network_security_v1alpha1.types.client_tls_policy import ListClientTlsPoliciesResponse -from google.cloud.network_security_v1alpha1.types.client_tls_policy import UpdateClientTlsPolicyRequest -from google.cloud.network_security_v1alpha1.types.common import OperationMetadata -from google.cloud.network_security_v1alpha1.types.tls import CertificateProvider -from google.cloud.network_security_v1alpha1.types.tls import CertificateProviderInstance -from google.cloud.network_security_v1alpha1.types.tls import GrpcEndpoint -from google.cloud.network_security_v1alpha1.types.tls import ValidationCA - -__all__ = ('NetworkSecurityClient', - 'NetworkSecurityAsyncClient', - 'ClientTlsPolicy', - 'CreateClientTlsPolicyRequest', - 'DeleteClientTlsPolicyRequest', - 'GetClientTlsPolicyRequest', - 'ListClientTlsPoliciesRequest', - 'ListClientTlsPoliciesResponse', - 'UpdateClientTlsPolicyRequest', - 'OperationMetadata', - 'CertificateProvider', - 'CertificateProviderInstance', - 'GrpcEndpoint', - 'ValidationCA', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/py.typed b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/py.typed deleted file mode 100644 index 41b3c3019247..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/__init__.py deleted file mode 100644 index b12276617bce..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/__init__.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.network_security_v1alpha1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.network_security import NetworkSecurityClient -from .services.network_security import NetworkSecurityAsyncClient - -from .types.client_tls_policy import ClientTlsPolicy -from .types.client_tls_policy import CreateClientTlsPolicyRequest -from .types.client_tls_policy import DeleteClientTlsPolicyRequest -from .types.client_tls_policy import GetClientTlsPolicyRequest -from .types.client_tls_policy import ListClientTlsPoliciesRequest -from .types.client_tls_policy import ListClientTlsPoliciesResponse -from .types.client_tls_policy import UpdateClientTlsPolicyRequest -from .types.common import OperationMetadata -from .types.tls import CertificateProvider -from .types.tls import CertificateProviderInstance -from .types.tls import GrpcEndpoint -from .types.tls import ValidationCA - -__all__ = ( - 'NetworkSecurityAsyncClient', -'CertificateProvider', -'CertificateProviderInstance', -'ClientTlsPolicy', -'CreateClientTlsPolicyRequest', -'DeleteClientTlsPolicyRequest', -'GetClientTlsPolicyRequest', -'GrpcEndpoint', -'ListClientTlsPoliciesRequest', -'ListClientTlsPoliciesResponse', -'NetworkSecurityClient', -'OperationMetadata', -'UpdateClientTlsPolicyRequest', -'ValidationCA', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_metadata.json deleted file mode 100644 index 2dcb3d449f64..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_metadata.json +++ /dev/null @@ -1,103 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.network_security_v1alpha1", - "protoPackage": "google.cloud.networksecurity.v1alpha1", - "schema": "1.0", - "services": { - "NetworkSecurity": { - "clients": { - "grpc": { - "libraryClient": "NetworkSecurityClient", - "rpcs": { - "CreateClientTlsPolicy": { - "methods": [ - "create_client_tls_policy" - ] - }, - "DeleteClientTlsPolicy": { - "methods": [ - "delete_client_tls_policy" - ] - }, - "GetClientTlsPolicy": { - "methods": [ - "get_client_tls_policy" - ] - }, - "ListClientTlsPolicies": { - "methods": [ - "list_client_tls_policies" - ] - }, - "UpdateClientTlsPolicy": { - "methods": [ - "update_client_tls_policy" - ] - } - } - }, - "grpc-async": { - "libraryClient": "NetworkSecurityAsyncClient", - "rpcs": { - "CreateClientTlsPolicy": { - "methods": [ - "create_client_tls_policy" - ] - }, - "DeleteClientTlsPolicy": { - "methods": [ - "delete_client_tls_policy" - ] - }, - "GetClientTlsPolicy": { - "methods": [ - "get_client_tls_policy" - ] - }, - "ListClientTlsPolicies": { - "methods": [ - "list_client_tls_policies" - ] - }, - "UpdateClientTlsPolicy": { - "methods": [ - "update_client_tls_policy" - ] - } - } - }, - "rest": { - "libraryClient": "NetworkSecurityClient", - "rpcs": { - "CreateClientTlsPolicy": { - "methods": [ - "create_client_tls_policy" - ] - }, - "DeleteClientTlsPolicy": { - "methods": [ - "delete_client_tls_policy" - ] - }, - "GetClientTlsPolicy": { - "methods": [ - "get_client_tls_policy" - ] - }, - "ListClientTlsPolicies": { - "methods": [ - "list_client_tls_policies" - ] - }, - "UpdateClientTlsPolicy": { - "methods": [ - "update_client_tls_policy" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/py.typed b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/py.typed deleted file mode 100644 index 41b3c3019247..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/__init__.py deleted file mode 100644 index cbf94b283c70..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/__init__.py deleted file mode 100644 index cddb3cfba9e6..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 NetworkSecurityClient -from .async_client import NetworkSecurityAsyncClient - -__all__ = ( - 'NetworkSecurityClient', - 'NetworkSecurityAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/async_client.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/async_client.py deleted file mode 100644 index 8d885d988570..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/async_client.py +++ /dev/null @@ -1,1539 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.network_security_v1alpha1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1alpha1.services.network_security import pagers -from google.cloud.network_security_v1alpha1.types import client_tls_policy -from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1alpha1.types import common -from google.cloud.network_security_v1alpha1.types import tls -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport -from .client import NetworkSecurityClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class NetworkSecurityAsyncClient: - """Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - """ - - _client: NetworkSecurityClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = NetworkSecurityClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = NetworkSecurityClient._DEFAULT_UNIVERSE - - client_tls_policy_path = staticmethod(NetworkSecurityClient.client_tls_policy_path) - parse_client_tls_policy_path = staticmethod(NetworkSecurityClient.parse_client_tls_policy_path) - common_billing_account_path = staticmethod(NetworkSecurityClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(NetworkSecurityClient.parse_common_billing_account_path) - common_folder_path = staticmethod(NetworkSecurityClient.common_folder_path) - parse_common_folder_path = staticmethod(NetworkSecurityClient.parse_common_folder_path) - common_organization_path = staticmethod(NetworkSecurityClient.common_organization_path) - parse_common_organization_path = staticmethod(NetworkSecurityClient.parse_common_organization_path) - common_project_path = staticmethod(NetworkSecurityClient.common_project_path) - parse_common_project_path = staticmethod(NetworkSecurityClient.parse_common_project_path) - common_location_path = staticmethod(NetworkSecurityClient.common_location_path) - parse_common_location_path = staticmethod(NetworkSecurityClient.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: - NetworkSecurityAsyncClient: The constructed client. - """ - return NetworkSecurityClient.from_service_account_info.__func__(NetworkSecurityAsyncClient, 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: - NetworkSecurityAsyncClient: The constructed client. - """ - return NetworkSecurityClient.from_service_account_file.__func__(NetworkSecurityAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return NetworkSecurityClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> NetworkSecurityTransport: - """Returns the transport used by the client instance. - - Returns: - NetworkSecurityTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = NetworkSecurityClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the network security async 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the NetworkSecurityTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client = NetworkSecurityClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient`.", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "credentialsType": None, - } - ) - - async def list_client_tls_policies(self, - request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListClientTlsPoliciesAsyncPager: - r"""Lists ClientTlsPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1alpha1 - - async def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest, dict]]): - The request object. Request used by the - ListClientTlsPolicies method. - parent (:class:`str`): - Required. The project and location from which the - ClientTlsPolicies should be listed, specified in the - format ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1alpha1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager: - Response returned by the - ListClientTlsPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): - request = client_tls_policy.ListClientTlsPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_client_tls_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.ListClientTlsPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_client_tls_policy(self, - request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> client_tls_policy.ClientTlsPolicy: - r"""Gets details of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1alpha1 - - async def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1alpha1.types.GetClientTlsPolicyRequest, dict]]): - The request object. Request used by the - GetClientTlsPolicy method. - name (:class:`str`): - Required. A name of the ClientTlsPolicy to get. Must be - in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1alpha1.types.ClientTlsPolicy: - ClientTlsPolicy is a resource that - specifies how a client should - authenticate connections to backends of - a service. This resource itself does not - affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): - request = client_tls_policy.GetClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - client_tls_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new ClientTlsPolicy in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1alpha1 - - async def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1alpha1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1alpha1.types.CreateClientTlsPolicyRequest, dict]]): - The request object. Request used by the - CreateClientTlsPolicy method. - parent (:class:`str`): - Required. The parent resource of the ClientTlsPolicy. - Must be in the format - ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy (:class:`google.cloud.network_security_v1alpha1.types.ClientTlsPolicy`): - Required. ClientTlsPolicy resource to - be created. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy_id (:class:`str`): - Required. Short name of the ClientTlsPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "client_mtls_policy". - - This corresponds to the ``client_tls_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1alpha1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, client_tls_policy, client_tls_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if client_tls_policy_id is not None: - request.client_tls_policy_id = client_tls_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, - *, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1alpha1 - - async def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1alpha1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1alpha1.types.UpdateClientTlsPolicyRequest, dict]]): - The request object. Request used by UpdateClientTlsPolicy - method. - client_tls_policy (:class:`google.cloud.network_security_v1alpha1.types.ClientTlsPolicy`): - Required. Updated ClientTlsPolicy - resource. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Field mask is used to specify the fields to be - overwritten in the ClientTlsPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1alpha1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [client_tls_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_client_tls_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("client_tls_policy.name", request.client_tls_policy.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_client_tls_policy(self, - request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1alpha1 - - async def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1alpha1.types.DeleteClientTlsPolicyRequest, dict]]): - The request object. Request used by the - DeleteClientTlsPolicy method. - name (:class:`str`): - Required. A name of the ClientTlsPolicy to delete. Must - be in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): - request = client_tls_policy.DeleteClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_operations] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_location] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_locations] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "NetworkSecurityAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -__all__ = ( - "NetworkSecurityAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/client.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/client.py deleted file mode 100644 index c166889d6e8f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/client.py +++ /dev/null @@ -1,1918 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 http import HTTPStatus -import json -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.network_security_v1alpha1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1alpha1.services.network_security import pagers -from google.cloud.network_security_v1alpha1.types import client_tls_policy -from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1alpha1.types import common -from google.cloud.network_security_v1alpha1.types import tls -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import NetworkSecurityGrpcTransport -from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport -from .transports.rest import NetworkSecurityRestTransport - - -class NetworkSecurityClientMeta(type): - """Metaclass for the NetworkSecurity 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[NetworkSecurityTransport]] - _transport_registry["grpc"] = NetworkSecurityGrpcTransport - _transport_registry["grpc_asyncio"] = NetworkSecurityGrpcAsyncIOTransport - _transport_registry["rest"] = NetworkSecurityRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[NetworkSecurityTransport]: - """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 NetworkSecurityClient(metaclass=NetworkSecurityClientMeta): - """Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - """ - - @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") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "networksecurity.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "networksecurity.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @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: - NetworkSecurityClient: 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: - NetworkSecurityClient: 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) -> NetworkSecurityTransport: - """Returns the transport used by the client instance. - - Returns: - NetworkSecurityTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def client_tls_policy_path(project: str,location: str,client_tls_policy: str,) -> str: - """Returns a fully-qualified client_tls_policy string.""" - return "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) - - @staticmethod - def parse_client_tls_policy_path(path: str) -> Dict[str,str]: - """Parses a client_tls_policy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clientTlsPolicies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = NetworkSecurityClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError - ) -> None: - """Adds credential info string to error details for 401/403/404 errors. - - Args: - error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. - """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the network security 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the NetworkSecurityTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = NetworkSecurityClient._read_environment_variables() - self._client_cert_source = NetworkSecurityClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = NetworkSecurityClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, NetworkSecurityTransport) - if transport_provided: - # transport is a NetworkSecurityTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(NetworkSecurityTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - NetworkSecurityClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[NetworkSecurityTransport], Callable[..., NetworkSecurityTransport]] = ( - NetworkSecurityClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., NetworkSecurityTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.networksecurity_v1alpha1.NetworkSecurityClient`.", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "credentialsType": None, - } - ) - - def list_client_tls_policies(self, - request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListClientTlsPoliciesPager: - r"""Lists ClientTlsPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1alpha1 - - def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest, dict]): - The request object. Request used by the - ListClientTlsPolicies method. - parent (str): - Required. The project and location from which the - ClientTlsPolicies should be listed, specified in the - format ``projects/*/locations/{location}``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1alpha1.services.network_security.pagers.ListClientTlsPoliciesPager: - Response returned by the - ListClientTlsPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): - request = client_tls_policy.ListClientTlsPoliciesRequest(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_client_tls_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.ListClientTlsPoliciesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_client_tls_policy(self, - request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> client_tls_policy.ClientTlsPolicy: - r"""Gets details of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1alpha1 - - def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1alpha1.types.GetClientTlsPolicyRequest, dict]): - The request object. Request used by the - GetClientTlsPolicy method. - name (str): - Required. A name of the ClientTlsPolicy to get. Must be - in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1alpha1.types.ClientTlsPolicy: - ClientTlsPolicy is a resource that - specifies how a client should - authenticate connections to backends of - a service. This resource itself does not - affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): - request = client_tls_policy.GetClientTlsPolicyRequest(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_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - client_tls_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new ClientTlsPolicy in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1alpha1 - - def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1alpha1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1alpha1.types.CreateClientTlsPolicyRequest, dict]): - The request object. Request used by the - CreateClientTlsPolicy method. - parent (str): - Required. The parent resource of the ClientTlsPolicy. - Must be in the format - ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy (google.cloud.network_security_v1alpha1.types.ClientTlsPolicy): - Required. ClientTlsPolicy resource to - be created. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy_id (str): - Required. Short name of the ClientTlsPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "client_mtls_policy". - - This corresponds to the ``client_tls_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1alpha1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, client_tls_policy, client_tls_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if client_tls_policy_id is not None: - request.client_tls_policy_id = client_tls_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, - *, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1alpha1 - - def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1alpha1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1alpha1.types.UpdateClientTlsPolicyRequest, dict]): - The request object. Request used by UpdateClientTlsPolicy - method. - client_tls_policy (google.cloud.network_security_v1alpha1.types.ClientTlsPolicy): - Required. Updated ClientTlsPolicy - resource. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the ClientTlsPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1alpha1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [client_tls_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_client_tls_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("client_tls_policy.name", request.client_tls_policy.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_client_tls_policy(self, - request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1alpha1 - - def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1alpha1.types.DeleteClientTlsPolicyRequest, dict]): - The request object. Request used by the - DeleteClientTlsPolicy method. - name (str): - Required. A name of the ClientTlsPolicy to delete. Must - be in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): - request = client_tls_policy.DeleteClientTlsPolicyRequest(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_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "NetworkSecurityClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_operations] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.cancel_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_location] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_locations] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - -__all__ = ( - "NetworkSecurityClient", -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/pagers.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/pagers.py deleted file mode 100644 index d1879e70eb7e..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/pagers.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.cloud.network_security_v1alpha1.types import client_tls_policy - - -class ListClientTlsPoliciesPager: - """A pager for iterating through ``list_client_tls_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``client_tls_policies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListClientTlsPolicies`` requests and continue to iterate - through the ``client_tls_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse` - 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[..., client_tls_policy.ListClientTlsPoliciesResponse], - request: client_tls_policy.ListClientTlsPoliciesRequest, - response: client_tls_policy.ListClientTlsPoliciesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[client_tls_policy.ListClientTlsPoliciesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[client_tls_policy.ClientTlsPolicy]: - for page in self.pages: - yield from page.client_tls_policies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListClientTlsPoliciesAsyncPager: - """A pager for iterating through ``list_client_tls_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``client_tls_policies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListClientTlsPolicies`` requests and continue to iterate - through the ``client_tls_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse` - 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[client_tls_policy.ListClientTlsPoliciesResponse]], - request: client_tls_policy.ListClientTlsPoliciesRequest, - response: client_tls_policy.ListClientTlsPoliciesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[client_tls_policy.ListClientTlsPoliciesResponse]: - 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[client_tls_policy.ClientTlsPolicy]: - async def async_generator(): - async for page in self.pages: - for response in page.client_tls_policies: - 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/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/README.rst b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/README.rst deleted file mode 100644 index e226a3cdbadb..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`NetworkSecurityTransport` is the ABC for all transports. -- public child `NetworkSecurityGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `NetworkSecurityGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseNetworkSecurityRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `NetworkSecurityRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/__init__.py deleted file mode 100644 index 6ee9817a2d9e..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 NetworkSecurityTransport -from .grpc import NetworkSecurityGrpcTransport -from .grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport -from .rest import NetworkSecurityRestTransport -from .rest import NetworkSecurityRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[NetworkSecurityTransport]] -_transport_registry['grpc'] = NetworkSecurityGrpcTransport -_transport_registry['grpc_asyncio'] = NetworkSecurityGrpcAsyncIOTransport -_transport_registry['rest'] = NetworkSecurityRestTransport - -__all__ = ( - 'NetworkSecurityTransport', - 'NetworkSecurityGrpcTransport', - 'NetworkSecurityGrpcAsyncIOTransport', - 'NetworkSecurityRestTransport', - 'NetworkSecurityRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/base.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/base.py deleted file mode 100644 index de50919c0308..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/base.py +++ /dev/null @@ -1,353 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.network_security_v1alpha1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1alpha1.types import client_tls_policy -from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class NetworkSecurityTransport(abc.ABC): - """Abstract transport class for NetworkSecurity.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'networksecurity.googleapis.com' - - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # 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 and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_client_tls_policies: gapic_v1.method.wrap_method( - self.list_client_tls_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_client_tls_policy: gapic_v1.method.wrap_method( - self.get_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_client_tls_policy: gapic_v1.method.wrap_method( - self.create_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_client_tls_policy: gapic_v1.method.wrap_method( - self.update_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_client_tls_policy: gapic_v1.method.wrap_method( - self.delete_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - Union[ - client_tls_policy.ListClientTlsPoliciesResponse, - Awaitable[client_tls_policy.ListClientTlsPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - Union[ - client_tls_policy.ClientTlsPolicy, - Awaitable[client_tls_policy.ClientTlsPolicy] - ]]: - raise NotImplementedError() - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'NetworkSecurityTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc.py deleted file mode 100644 index de9a0a9e447c..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc.py +++ /dev/null @@ -1,664 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 json -import logging as std_logging -import pickle -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1alpha1.types import client_tls_policy -from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class NetworkSecurityGrpcTransport(NetworkSecurityTransport): - """gRPC backend transport for NetworkSecurity. - - Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - - 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - client_tls_policy.ListClientTlsPoliciesResponse]: - r"""Return a callable for the list client tls policies method over gRPC. - - Lists ClientTlsPolicies in a given project and - location. - - Returns: - Callable[[~.ListClientTlsPoliciesRequest], - ~.ListClientTlsPoliciesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: - self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/ListClientTlsPolicies', - request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, - response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, - ) - return self._stubs['list_client_tls_policies'] - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - client_tls_policy.ClientTlsPolicy]: - r"""Return a callable for the get client tls policy method over gRPC. - - Gets details of a single ClientTlsPolicy. - - Returns: - Callable[[~.GetClientTlsPolicyRequest], - ~.ClientTlsPolicy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: - self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/GetClientTlsPolicy', - request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, - response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, - ) - return self._stubs['get_client_tls_policy'] - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the create client tls policy method over gRPC. - - Creates a new ClientTlsPolicy in a given project and - location. - - Returns: - Callable[[~.CreateClientTlsPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_client_tls_policy' not in self._stubs: - self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/CreateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_client_tls_policy'] - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the update client tls policy method over gRPC. - - Updates the parameters of a single ClientTlsPolicy. - - Returns: - Callable[[~.UpdateClientTlsPolicyRequest], - ~.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 'update_client_tls_policy' not in self._stubs: - self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/UpdateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_client_tls_policy'] - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete client tls policy method over gRPC. - - Deletes a single ClientTlsPolicy. - - Returns: - Callable[[~.DeleteClientTlsPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_client_tls_policy' not in self._stubs: - self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/DeleteClientTlsPolicy', - request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_client_tls_policy'] - - def close(self): - self._logged_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'NetworkSecurityGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc_asyncio.py deleted file mode 100644 index d86c9fd628f3..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/grpc_asyncio.py +++ /dev/null @@ -1,750 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 inspect -import json -import pickle -import logging as std_logging -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1alpha1.types import client_tls_policy -from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO -from .grpc import NetworkSecurityGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class NetworkSecurityGrpcAsyncIOTransport(NetworkSecurityTransport): - """gRPC AsyncIO backend transport for NetworkSecurity. - - Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - - 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - Awaitable[client_tls_policy.ListClientTlsPoliciesResponse]]: - r"""Return a callable for the list client tls policies method over gRPC. - - Lists ClientTlsPolicies in a given project and - location. - - Returns: - Callable[[~.ListClientTlsPoliciesRequest], - Awaitable[~.ListClientTlsPoliciesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: - self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/ListClientTlsPolicies', - request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, - response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, - ) - return self._stubs['list_client_tls_policies'] - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - Awaitable[client_tls_policy.ClientTlsPolicy]]: - r"""Return a callable for the get client tls policy method over gRPC. - - Gets details of a single ClientTlsPolicy. - - Returns: - Callable[[~.GetClientTlsPolicyRequest], - Awaitable[~.ClientTlsPolicy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: - self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/GetClientTlsPolicy', - request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, - response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, - ) - return self._stubs['get_client_tls_policy'] - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create client tls policy method over gRPC. - - Creates a new ClientTlsPolicy in a given project and - location. - - Returns: - Callable[[~.CreateClientTlsPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_client_tls_policy' not in self._stubs: - self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/CreateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_client_tls_policy'] - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update client tls policy method over gRPC. - - Updates the parameters of a single ClientTlsPolicy. - - Returns: - Callable[[~.UpdateClientTlsPolicyRequest], - 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 'update_client_tls_policy' not in self._stubs: - self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/UpdateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_client_tls_policy'] - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete client tls policy method over gRPC. - - Deletes a single ClientTlsPolicy. - - Returns: - Callable[[~.DeleteClientTlsPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_client_tls_policy' not in self._stubs: - self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1alpha1.NetworkSecurity/DeleteClientTlsPolicy', - request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_client_tls_policy'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_client_tls_policies: self._wrap_method( - self.list_client_tls_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_client_tls_policy: self._wrap_method( - self.get_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_client_tls_policy: self._wrap_method( - self.create_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_client_tls_policy: self._wrap_method( - self.update_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_client_tls_policy: self._wrap_method( - self.delete_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'NetworkSecurityGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest.py deleted file mode 100644 index e1452ae85d00..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest.py +++ /dev/null @@ -1,2341 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 -import google.protobuf - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.network_security_v1alpha1.types import client_tls_policy -from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseNetworkSecurityRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class NetworkSecurityRestInterceptor: - """Interceptor for NetworkSecurity. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the NetworkSecurityRestTransport. - - .. code-block:: python - class MyCustomNetworkSecurityInterceptor(NetworkSecurityRestInterceptor): - def pre_create_client_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_client_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_client_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_client_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_client_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_client_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_client_tls_policies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_client_tls_policies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_client_tls_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_client_tls_policy(self, response): - logging.log(f"Received response: {response}") - return response - - transport = NetworkSecurityRestTransport(interceptor=MyCustomNetworkSecurityInterceptor()) - client = NetworkSecurityClient(transport=transport) - - - """ - def pre_create_client_tls_policy(self, request: gcn_client_tls_policy.CreateClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_client_tls_policy.CreateClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_client_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_create_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_client_tls_policy - - DEPRECATED. Please use the `post_create_client_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_create_client_tls_policy` interceptor runs - before the `post_create_client_tls_policy_with_metadata` interceptor. - """ - return response - - def post_create_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_client_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_create_client_tls_policy_with_metadata` - interceptor in new development instead of the `post_create_client_tls_policy` interceptor. - When both interceptors are used, this `post_create_client_tls_policy_with_metadata` interceptor runs after the - `post_create_client_tls_policy` interceptor. The (possibly modified) response returned by - `post_create_client_tls_policy` will be passed to - `post_create_client_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_delete_client_tls_policy(self, request: client_tls_policy.DeleteClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.DeleteClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_client_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_delete_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_client_tls_policy - - DEPRECATED. Please use the `post_delete_client_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_delete_client_tls_policy` interceptor runs - before the `post_delete_client_tls_policy_with_metadata` interceptor. - """ - return response - - def post_delete_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for delete_client_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_delete_client_tls_policy_with_metadata` - interceptor in new development instead of the `post_delete_client_tls_policy` interceptor. - When both interceptors are used, this `post_delete_client_tls_policy_with_metadata` interceptor runs after the - `post_delete_client_tls_policy` interceptor. The (possibly modified) response returned by - `post_delete_client_tls_policy` will be passed to - `post_delete_client_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_get_client_tls_policy(self, request: client_tls_policy.GetClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.GetClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_client_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_get_client_tls_policy(self, response: client_tls_policy.ClientTlsPolicy) -> client_tls_policy.ClientTlsPolicy: - """Post-rpc interceptor for get_client_tls_policy - - DEPRECATED. Please use the `post_get_client_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_get_client_tls_policy` interceptor runs - before the `post_get_client_tls_policy_with_metadata` interceptor. - """ - return response - - def post_get_client_tls_policy_with_metadata(self, response: client_tls_policy.ClientTlsPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ClientTlsPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_client_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_get_client_tls_policy_with_metadata` - interceptor in new development instead of the `post_get_client_tls_policy` interceptor. - When both interceptors are used, this `post_get_client_tls_policy_with_metadata` interceptor runs after the - `post_get_client_tls_policy` interceptor. The (possibly modified) response returned by - `post_get_client_tls_policy` will be passed to - `post_get_client_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_list_client_tls_policies(self, request: client_tls_policy.ListClientTlsPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ListClientTlsPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_client_tls_policies - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_list_client_tls_policies(self, response: client_tls_policy.ListClientTlsPoliciesResponse) -> client_tls_policy.ListClientTlsPoliciesResponse: - """Post-rpc interceptor for list_client_tls_policies - - DEPRECATED. Please use the `post_list_client_tls_policies_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_list_client_tls_policies` interceptor runs - before the `post_list_client_tls_policies_with_metadata` interceptor. - """ - return response - - def post_list_client_tls_policies_with_metadata(self, response: client_tls_policy.ListClientTlsPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[client_tls_policy.ListClientTlsPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_client_tls_policies - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_list_client_tls_policies_with_metadata` - interceptor in new development instead of the `post_list_client_tls_policies` interceptor. - When both interceptors are used, this `post_list_client_tls_policies_with_metadata` interceptor runs after the - `post_list_client_tls_policies` interceptor. The (possibly modified) response returned by - `post_list_client_tls_policies` will be passed to - `post_list_client_tls_policies_with_metadata`. - """ - return response, metadata - - def pre_update_client_tls_policy(self, request: gcn_client_tls_policy.UpdateClientTlsPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_client_tls_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_update_client_tls_policy(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_client_tls_policy - - DEPRECATED. Please use the `post_update_client_tls_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. This `post_update_client_tls_policy` interceptor runs - before the `post_update_client_tls_policy_with_metadata` interceptor. - """ - return response - - def post_update_client_tls_policy_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_client_tls_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the NetworkSecurity server but before it is returned to user code. - - We recommend only using this `post_update_client_tls_policy_with_metadata` - interceptor in new development instead of the `post_update_client_tls_policy` interceptor. - When both interceptors are used, this `post_update_client_tls_policy_with_metadata` interceptor runs after the - `post_update_client_tls_policy` interceptor. The (possibly modified) response returned by - `post_update_client_tls_policy` will be passed to - `post_update_client_tls_policy_with_metadata`. - """ - return response, metadata - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the NetworkSecurity server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the NetworkSecurity server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class NetworkSecurityRestStub: - _session: AuthorizedSession - _host: str - _interceptor: NetworkSecurityRestInterceptor - - -class NetworkSecurityRestTransport(_BaseNetworkSecurityRestTransport): - """REST backend synchronous transport for NetworkSecurity. - - Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[NetworkSecurityRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or NetworkSecurityRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'delete', - 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha1/{name=organizations/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1alpha1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.CreateClientTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: gcn_client_tls_policy.CreateClientTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create client tls policy method over HTTP. - - Args: - request (~.gcn_client_tls_policy.CreateClientTlsPolicyRequest): - The request object. Request used by the - CreateClientTlsPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_create_client_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.CreateClientTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "CreateClientTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._CreateClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_client_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_client_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.create_client_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "CreateClientTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.DeleteClientTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: client_tls_policy.DeleteClientTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete client tls policy method over HTTP. - - Args: - request (~.client_tls_policy.DeleteClientTlsPolicyRequest): - The request object. Request used by the - DeleteClientTlsPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_delete_client_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.DeleteClientTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "DeleteClientTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._DeleteClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_delete_client_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_client_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.delete_client_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "DeleteClientTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.GetClientTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: client_tls_policy.GetClientTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> client_tls_policy.ClientTlsPolicy: - r"""Call the get client tls policy method over HTTP. - - Args: - request (~.client_tls_policy.GetClientTlsPolicyRequest): - The request object. Request used by the - GetClientTlsPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.client_tls_policy.ClientTlsPolicy: - ClientTlsPolicy is a resource that - specifies how a client should - authenticate connections to backends of - a service. This resource itself does not - affect configuration unless it is - attached to a backend service resource. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_get_client_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.GetClientTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "GetClientTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._GetClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = client_tls_policy.ClientTlsPolicy() - pb_resp = client_tls_policy.ClientTlsPolicy.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_client_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_client_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = client_tls_policy.ClientTlsPolicy.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.get_client_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "GetClientTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListClientTlsPolicies(_BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.ListClientTlsPolicies") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: client_tls_policy.ListClientTlsPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> client_tls_policy.ListClientTlsPoliciesResponse: - r"""Call the list client tls policies method over HTTP. - - Args: - request (~.client_tls_policy.ListClientTlsPoliciesRequest): - The request object. Request used by the - ListClientTlsPolicies method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.client_tls_policy.ListClientTlsPoliciesResponse: - Response returned by the - ListClientTlsPolicies method. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_http_options() - - request, metadata = self._interceptor.pre_list_client_tls_policies(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.ListClientTlsPolicies", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "ListClientTlsPolicies", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._ListClientTlsPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = client_tls_policy.ListClientTlsPoliciesResponse() - pb_resp = client_tls_policy.ListClientTlsPoliciesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_client_tls_policies(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_client_tls_policies_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = client_tls_policy.ListClientTlsPoliciesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.list_client_tls_policies", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "ListClientTlsPolicies", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateClientTlsPolicy(_BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.UpdateClientTlsPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: gcn_client_tls_policy.UpdateClientTlsPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update client tls policy method over HTTP. - - Args: - request (~.gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - The request object. Request used by UpdateClientTlsPolicy - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_http_options() - - request, metadata = self._interceptor.pre_update_client_tls_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.UpdateClientTlsPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "UpdateClientTlsPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._UpdateClientTlsPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_client_tls_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_client_tls_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.update_client_tls_policy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "UpdateClientTlsPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - client_tls_policy.ClientTlsPolicy]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - client_tls_policy.ListClientTlsPoliciesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListClientTlsPolicies(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateClientTlsPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseNetworkSecurityRestTransport._BaseGetLocation, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_http_options() - - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.GetLocation", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "GetLocation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.GetLocation", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "GetLocation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseNetworkSecurityRestTransport._BaseListLocations, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseListLocations._get_http_options() - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.ListLocations", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "ListLocations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.ListLocations", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "ListLocations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseNetworkSecurityRestTransport._BaseGetIamPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_http_options() - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.GetIamPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "GetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.GetIamPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "GetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseNetworkSecurityRestTransport._BaseSetIamPolicy, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_http_options() - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.SetIamPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "SetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.SetIamPolicy", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "SetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseNetworkSecurityRestTransport._BaseTestIamPermissions, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_http_options() - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.TestIamPermissions", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "TestIamPermissions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.TestIamPermissions", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "TestIamPermissions", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseNetworkSecurityRestTransport._BaseCancelOperation, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_http_options() - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.CancelOperation", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "CancelOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseNetworkSecurityRestTransport._BaseDeleteOperation, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_http_options() - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.DeleteOperation", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseNetworkSecurityRestTransport._BaseGetOperation, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.GetOperation", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.GetOperation", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "GetOperation", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseNetworkSecurityRestTransport._BaseListOperations, NetworkSecurityRestStub): - def __hash__(self): - return hash("NetworkSecurityRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseNetworkSecurityRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseNetworkSecurityRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseNetworkSecurityRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.cloud.networksecurity_v1alpha1.NetworkSecurityClient.ListOperations", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = NetworkSecurityRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.cloud.networksecurity_v1alpha1.NetworkSecurityAsyncClient.ListOperations", - extra = { - "serviceName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "rpcName": "ListOperations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'NetworkSecurityRestTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest_base.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest_base.py deleted file mode 100644 index 958a3c47aa85..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/services/network_security/transports/rest_base.py +++ /dev/null @@ -1,614 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.network_security_v1alpha1.types import client_tls_policy -from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseNetworkSecurityRestTransport(NetworkSecurityTransport): - """Base REST backend transport for NetworkSecurity. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - credentials (Optional[Any]): 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. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseCreateClientTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "clientTlsPolicyId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha1/{parent=projects/*/locations/*}/clientTlsPolicies', - 'body': 'client_tls_policy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseCreateClientTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteClientTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1alpha1/{name=projects/*/locations/*/clientTlsPolicies/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = client_tls_policy.DeleteClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseDeleteClientTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetClientTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha1/{name=projects/*/locations/*/clientTlsPolicies/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = client_tls_policy.GetClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseGetClientTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListClientTlsPolicies: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha1/{parent=projects/*/locations/*}/clientTlsPolicies', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = client_tls_policy.ListClientTlsPoliciesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseListClientTlsPolicies._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateClientTlsPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1alpha1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}', - 'body': 'client_tls_policy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseNetworkSecurityRestTransport._BaseUpdateClientTlsPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLocation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha1/{name=projects/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListLocations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha1/{name=projects/*}/locations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/authzPolicies/*}:getIamPolicy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/authzPolicies/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1alpha1/{resource=projects/*/locations/*/authzPolicies/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseCancelOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseDeleteOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'delete', - 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha1/{name=organizations/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListOperations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha1/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha1/{name=organizations/*/locations/*}/operations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseNetworkSecurityRestTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/__init__.py deleted file mode 100644 index 56e5949f4e2f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/__init__.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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_tls_policy import ( - ClientTlsPolicy, - CreateClientTlsPolicyRequest, - DeleteClientTlsPolicyRequest, - GetClientTlsPolicyRequest, - ListClientTlsPoliciesRequest, - ListClientTlsPoliciesResponse, - UpdateClientTlsPolicyRequest, -) -from .common import ( - OperationMetadata, -) -from .tls import ( - CertificateProvider, - CertificateProviderInstance, - GrpcEndpoint, - ValidationCA, -) - -__all__ = ( - 'ClientTlsPolicy', - 'CreateClientTlsPolicyRequest', - 'DeleteClientTlsPolicyRequest', - 'GetClientTlsPolicyRequest', - 'ListClientTlsPoliciesRequest', - 'ListClientTlsPoliciesResponse', - 'UpdateClientTlsPolicyRequest', - 'OperationMetadata', - 'CertificateProvider', - 'CertificateProviderInstance', - 'GrpcEndpoint', - 'ValidationCA', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/client_tls_policy.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/client_tls_policy.py deleted file mode 100644 index f40670b490de..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/client_tls_policy.py +++ /dev/null @@ -1,271 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.network_security_v1alpha1.types import tls -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1alpha1', - manifest={ - 'ClientTlsPolicy', - 'ListClientTlsPoliciesRequest', - 'ListClientTlsPoliciesResponse', - 'GetClientTlsPolicyRequest', - 'CreateClientTlsPolicyRequest', - 'UpdateClientTlsPolicyRequest', - 'DeleteClientTlsPolicyRequest', - }, -) - - -class ClientTlsPolicy(proto.Message): - r"""ClientTlsPolicy is a resource that specifies how a client - should authenticate connections to backends of a service. This - resource itself does not affect configuration unless it is - attached to a backend service resource. - - Attributes: - name (str): - Required. Name of the ClientTlsPolicy resource. It matches - the pattern - ``projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}`` - description (str): - Optional. Free-text description of the - resource. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was updated. - labels (MutableMapping[str, str]): - Optional. Set of label tags associated with - the resource. - sni (str): - Optional. Server Name Indication string to - present to the server during TLS handshake. E.g: - "secure.example.com". - client_certificate (google.cloud.network_security_v1alpha1.types.CertificateProvider): - Optional. Defines a mechanism to provision - client identity (public and private keys) for - peer to peer authentication. The presence of - this dictates mTLS. - server_validation_ca (MutableSequence[google.cloud.network_security_v1alpha1.types.ValidationCA]): - Optional. Defines the mechanism to obtain the - Certificate Authority certificate to validate - the server certificate. If empty, client does - not validate the server certificate. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - sni: str = proto.Field( - proto.STRING, - number=6, - ) - client_certificate: tls.CertificateProvider = proto.Field( - proto.MESSAGE, - number=7, - message=tls.CertificateProvider, - ) - server_validation_ca: MutableSequence[tls.ValidationCA] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=tls.ValidationCA, - ) - - -class ListClientTlsPoliciesRequest(proto.Message): - r"""Request used by the ListClientTlsPolicies method. - - Attributes: - parent (str): - Required. The project and location from which the - ClientTlsPolicies should be listed, specified in the format - ``projects/*/locations/{location}``. - page_size (int): - Maximum number of ClientTlsPolicies to return - per call. - page_token (str): - The value returned by the last - ``ListClientTlsPoliciesResponse`` Indicates that this is a - continuation of a prior ``ListClientTlsPolicies`` call, and - that the system should return the next page of data. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListClientTlsPoliciesResponse(proto.Message): - r"""Response returned by the ListClientTlsPolicies method. - - Attributes: - client_tls_policies (MutableSequence[google.cloud.network_security_v1alpha1.types.ClientTlsPolicy]): - List of ClientTlsPolicy resources. - next_page_token (str): - If there might be 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 - - client_tls_policies: MutableSequence['ClientTlsPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ClientTlsPolicy', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetClientTlsPolicyRequest(proto.Message): - r"""Request used by the GetClientTlsPolicy method. - - Attributes: - name (str): - Required. A name of the ClientTlsPolicy to get. Must be in - the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateClientTlsPolicyRequest(proto.Message): - r"""Request used by the CreateClientTlsPolicy method. - - Attributes: - parent (str): - Required. The parent resource of the ClientTlsPolicy. Must - be in the format ``projects/*/locations/{location}``. - client_tls_policy_id (str): - Required. Short name of the ClientTlsPolicy resource to be - created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and underscores, - and should not start with a number. E.g. - "client_mtls_policy". - client_tls_policy (google.cloud.network_security_v1alpha1.types.ClientTlsPolicy): - Required. ClientTlsPolicy resource to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - client_tls_policy_id: str = proto.Field( - proto.STRING, - number=2, - ) - client_tls_policy: 'ClientTlsPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='ClientTlsPolicy', - ) - - -class UpdateClientTlsPolicyRequest(proto.Message): - r"""Request used by UpdateClientTlsPolicy method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the ClientTlsPolicy resource by the update. - The fields specified in the update_mask are relative to the - resource, not the full request. A field will be overwritten - if it is in the mask. If the user does not provide a mask - then all fields will be overwritten. - client_tls_policy (google.cloud.network_security_v1alpha1.types.ClientTlsPolicy): - Required. Updated ClientTlsPolicy resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - client_tls_policy: 'ClientTlsPolicy' = proto.Field( - proto.MESSAGE, - number=2, - message='ClientTlsPolicy', - ) - - -class DeleteClientTlsPolicyRequest(proto.Message): - r"""Request used by the DeleteClientTlsPolicy method. - - Attributes: - name (str): - Required. A name of the ClientTlsPolicy to delete. Must be - in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/common.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/common.py deleted file mode 100644 index 8511c4469a9f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/common.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1alpha1', - manifest={ - 'OperationMetadata', - }, -) - - -class OperationMetadata(proto.Message): - r"""Represents the metadata of the long-running operation. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation was - created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation finished - running. - target (str): - Output only. Server-defined resource path for - the target of the operation. - verb (str): - Output only. Name of the verb executed by the - operation. - status_message (str): - Output only. Human-readable status of the - operation, if any. - requested_cancellation (bool): - Output only. Identifies whether the user has requested - cancellation of the operation. Operations that have - successfully been cancelled have [Operation.error][] value - with a [google.rpc.Status.code][google.rpc.Status.code] of - 1, corresponding to ``Code.CANCELLED``. - api_version (str): - Output only. API version used to start the - operation. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/network_security.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/network_security.py deleted file mode 100644 index f56d6b15fda0..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/network_security.py +++ /dev/null @@ -1,26 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1alpha1', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/tls.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/tls.py deleted file mode 100644 index 6474b41a2442..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/google/cloud/network_security_v1alpha1/types/tls.py +++ /dev/null @@ -1,197 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1alpha1', - manifest={ - 'GrpcEndpoint', - 'ValidationCA', - 'CertificateProviderInstance', - 'CertificateProvider', - }, -) - - -class GrpcEndpoint(proto.Message): - r"""Specification of the GRPC Endpoint. - - Attributes: - target_uri (str): - Required. The target URI of the gRPC - endpoint. Only UDS path is supported, and should - start with "unix:". - """ - - target_uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ValidationCA(proto.Message): - r"""Specification of ValidationCA. Defines the mechanism to - obtain the Certificate Authority certificate to validate the - peer certificate. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - ca_cert_path (str): - The path to the file holding the CA - certificate to validate the client or server - certificate. - - This field is a member of `oneof`_ ``type``. - grpc_endpoint (google.cloud.network_security_v1alpha1.types.GrpcEndpoint): - gRPC specific configuration to access the - gRPC server to obtain the CA certificate. - - This field is a member of `oneof`_ ``type``. - certificate_provider_instance (google.cloud.network_security_v1alpha1.types.CertificateProviderInstance): - The certificate provider instance - specification that will be passed to the data - plane, which will be used to load necessary - credential information. - - This field is a member of `oneof`_ ``type``. - """ - - ca_cert_path: str = proto.Field( - proto.STRING, - number=1, - oneof='type', - ) - grpc_endpoint: 'GrpcEndpoint' = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message='GrpcEndpoint', - ) - certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( - proto.MESSAGE, - number=3, - oneof='type', - message='CertificateProviderInstance', - ) - - -class CertificateProviderInstance(proto.Message): - r"""Specification of a TLS certificate provider instance. - Workloads may have one or more CertificateProvider instances - (plugins) and one of them is enabled and configured by - specifying this message. Workloads use the values from this - message to locate and load the CertificateProvider instance - configuration. - - Attributes: - plugin_instance (str): - Required. Plugin instance name, used to locate and load - CertificateProvider instance configuration. Set to - "google_cloud_private_spiffe" to use Certificate Authority - Service certificate provider instance. - """ - - plugin_instance: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CertificateProvider(proto.Message): - r"""Specification of certificate provider. Defines the mechanism - to obtain the certificate and private key for peer to peer - authentication. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - local_filepath (google.cloud.network_security_v1alpha1.types.CertificateProvider.TlsCertificateFiles): - Obtain certificates and private key from a - locally mounted filesystem path. - - This field is a member of `oneof`_ ``type``. - grpc_endpoint (google.cloud.network_security_v1alpha1.types.GrpcEndpoint): - gRPC specific configuration to access the - gRPC server to obtain the cert and private key. - - This field is a member of `oneof`_ ``type``. - certificate_provider_instance (google.cloud.network_security_v1alpha1.types.CertificateProviderInstance): - The certificate provider instance - specification that will be passed to the data - plane, which will be used to load necessary - credential information. - - This field is a member of `oneof`_ ``type``. - """ - - class TlsCertificateFiles(proto.Message): - r"""Specification of TLS certificate files. - - Attributes: - certificate_path (str): - Required. The path to the file that has the - certificate containing public key. - private_key_path (str): - Required. The path to the file that has the - private key. - """ - - certificate_path: str = proto.Field( - proto.STRING, - number=1, - ) - private_key_path: str = proto.Field( - proto.STRING, - number=2, - ) - - local_filepath: TlsCertificateFiles = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=TlsCertificateFiles, - ) - grpc_endpoint: 'GrpcEndpoint' = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message='GrpcEndpoint', - ) - certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( - proto.MESSAGE, - number=3, - oneof='type', - message='CertificateProviderInstance', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/mypy.ini b/owl-bot-staging/google-cloud-network-security/v1alpha1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/noxfile.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/noxfile.py deleted file mode 100644 index 6de174fa4528..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/noxfile.py +++ /dev/null @@ -1,592 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re -import shutil - -from typing import Dict, List -import warnings - -import nox - -BLACK_VERSION = "black[jupyter]==23.7.0" -ISORT_VERSION = "isort==5.11.0" - -LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = "google-cloud-network-security" - -UNIT_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "asyncmock", - "pytest", - "pytest-cov", - "pytest-asyncio", -] -UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_DEPENDENCIES: List[str] = [] -UNIT_TEST_EXTRAS: List[str] = [] -UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] -SYSTEM_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "pytest", - "google-cloud-testutils", -] -SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_EXTRAS: List[str] = [] -SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -nox.options.sessions = [ - "unit", - "system", - "cover", - "lint", - "lint_setup_py", - "blacken", - "docs", -] - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", - "types-requests", - "types-protobuf", - ) - session.install(".") - session.run( - "mypy", - "-p", - "google", - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "update", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "check", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *LINT_PATHS, - ) - - session.run("flake8", "google", "tests") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def format(session): - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run( - "isort", - "--fss", - *LINT_PATHS, - ) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("setuptools", "docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") - - -def install_unittest_dependencies(session, *constraints): - standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES - session.install(*standard_deps, *constraints) - - if UNIT_TEST_EXTERNAL_DEPENDENCIES: - warnings.warn( - "'unit_test_external_dependencies' is deprecated. Instead, please " - "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", - DeprecationWarning, - ) - session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_LOCAL_DEPENDENCIES: - session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_EXTRAS_BY_PYTHON: - extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif UNIT_TEST_EXTRAS: - extras = UNIT_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def unit(session, protobuf_implementation): - # Install all test dependencies, then install this package in-place. - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - install_unittest_dependencies(session, "-c", constraints_path) - - # TODO(https://github.com/googleapis/synthtool/issues/1976): - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - # Run py.test against the unit tests. - session.run( - "py.test", - "--quiet", - f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=google", - "--cov=tests/unit", - "--cov-append", - "--cov-config=.coveragerc", - "--cov-report=", - "--cov-fail-under=0", - os.path.join("tests", "unit"), - *session.posargs, - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -def install_systemtest_dependencies(session, *constraints): - session.install("--pre", "grpcio") - - session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: - session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_LOCAL_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTRAS_BY_PYTHON: - extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif SYSTEM_TEST_EXTRAS: - extras = SYSTEM_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) -def system(session): - """Run the system test suite.""" - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. - if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": - session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Install pyopenssl for mTLS testing. - if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": - session.install("pyopenssl") - - system_test_exists = os.path.exists(system_test_path) - system_test_folder_exists = os.path.exists(system_test_folder_path) - # Sanity check: only run tests if found. - if not system_test_exists and not system_test_folder_exists: - session.skip("System tests were not found") - - install_systemtest_dependencies(session, "-c", constraints_path) - - # Run py.test against the system tests. - if system_test_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if system_test_folder_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python="3.10") -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "sphinx==4.5.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", ""), - ) - - -@nox.session(python="3.10") -def docfx(session): - """Build the docfx yaml files for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "gcp-sphinx-docfx-yaml", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-D", - ( - "extensions=sphinx.ext.autodoc," - "sphinx.ext.autosummary," - "docfx_yaml.extension," - "sphinx.ext.intersphinx," - "sphinx.ext.coverage," - "sphinx.ext.napoleon," - "sphinx.ext.todo," - "sphinx.ext.viewcode," - "recommonmark" - ), - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def prerelease_deps(session, protobuf_implementation): - """ - Run all tests with pre-release versions of dependencies installed - rather than the standard non pre-release versions. - Pre-release versions can be installed using - `pip install --pre `. - """ - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # Note: If a dependency is added to the `prerel_deps` list, - # the `core_dependencies_from_source` list in the `core_deps_from_source` - # nox session should also be updated. - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpc-google-iam-v1", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--ignore-installed", dep) - # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` - # to the dictionary below once this bug is fixed. - # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add - # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below - # once this bug is fixed. - package_namespaces = { - "google-api-core": "google.api_core", - "google-auth": "google.auth", - "grpcio": "grpc", - "protobuf": "google.protobuf", - "proto-plus": "proto", - } - - version_namespace = package_namespaces.get(dep) - - print(f"Installed {dep}") - if version_namespace: - session.run( - "python", - "-c", - f"import {version_namespace}; print({version_namespace}.__version__)", - ) - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb"], -) -def core_deps_from_source(session, protobuf_implementation): - """Run all tests with core dependencies installed from source - rather than pulling the dependencies from PyPI. - """ - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and - # `grpcio-status` should be added to the list below so that they are installed from source, - # rather than PyPI. - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be - # added to the list below so that it is installed from source, rather than PyPI - # Note: If a dependency is added to the `core_dependencies_from_source` list, - # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. - core_dependencies_from_source = [ - "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", - "google-api-core @ git+https://github.com/googleapis/python-api-core.git", - "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", - "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", - "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", - ] - - for dep in core_dependencies_from_source: - session.install(dep, "--no-deps", "--ignore-installed") - print(f"Installed {dep}") - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py deleted file mode 100644 index ed74639eafa8..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1alpha1 - - -async def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1alpha1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py deleted file mode 100644 index f8438c277bf7..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1alpha1 - - -def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1alpha1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py deleted file mode 100644 index 79acd6b66664..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1alpha1 - - -async def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py deleted file mode 100644 index 55c9008c67f2..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1alpha1 - - -def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py deleted file mode 100644 index 1158ddae26f5..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1alpha1 - - -async def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py deleted file mode 100644 index 3ac60ffd0faa..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1alpha1 - - -def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py deleted file mode 100644 index 2d8699a86d01..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListClientTlsPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1alpha1 - - -async def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py deleted file mode 100644 index 4f77a060b847..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListClientTlsPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1alpha1 - - -def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1alpha1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py deleted file mode 100644 index 5a8ac0025c38..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1alpha1 - - -async def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1alpha1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py deleted file mode 100644 index 4bac529ce6ae..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1alpha1 - - -def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1alpha1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1alpha1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1alpha1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json b/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json deleted file mode 100644 index aca64a760d12..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1alpha1.json +++ /dev/null @@ -1,844 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.networksecurity.v1alpha1", - "version": "v1alpha1" - } - ], - "language": "PYTHON", - "name": "google-cloud-network-security", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient.create_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.CreateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1alpha1.types.CreateClientTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy" - }, - { - "name": "client_tls_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_client_tls_policy" - }, - "description": "Sample for CreateClientTlsPolicy", - "file": "networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient.create_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.CreateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1alpha1.types.CreateClientTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy" - }, - { - "name": "client_tls_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_client_tls_policy" - }, - "description": "Sample for CreateClientTlsPolicy", - "file": "networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_CreateClientTlsPolicy_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1alpha1_generated_network_security_create_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient.delete_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.DeleteClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1alpha1.types.DeleteClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_client_tls_policy" - }, - "description": "Sample for DeleteClientTlsPolicy", - "file": "networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient.delete_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.DeleteClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1alpha1.types.DeleteClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_client_tls_policy" - }, - "description": "Sample for DeleteClientTlsPolicy", - "file": "networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1alpha1_generated_network_security_delete_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient.get_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.GetClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1alpha1.types.GetClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy", - "shortName": "get_client_tls_policy" - }, - "description": "Sample for GetClientTlsPolicy", - "file": "networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient.get_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.GetClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1alpha1.types.GetClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy", - "shortName": "get_client_tls_policy" - }, - "description": "Sample for GetClientTlsPolicy", - "file": "networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_GetClientTlsPolicy_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1alpha1_generated_network_security_get_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient.list_client_tls_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.ListClientTlsPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListClientTlsPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1alpha1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager", - "shortName": "list_client_tls_policies" - }, - "description": "Sample for ListClientTlsPolicies", - "file": "networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient.list_client_tls_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.ListClientTlsPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListClientTlsPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1alpha1.types.ListClientTlsPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1alpha1.services.network_security.pagers.ListClientTlsPoliciesPager", - "shortName": "list_client_tls_policies" - }, - "description": "Sample for ListClientTlsPolicies", - "file": "networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_ListClientTlsPolicies_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1alpha1_generated_network_security_list_client_tls_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityAsyncClient.update_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.UpdateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1alpha1.types.UpdateClientTlsPolicyRequest" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_client_tls_policy" - }, - "description": "Sample for UpdateClientTlsPolicy", - "file": "networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1alpha1.NetworkSecurityClient.update_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity.UpdateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1alpha1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1alpha1.types.UpdateClientTlsPolicyRequest" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1alpha1.types.ClientTlsPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_client_tls_policy" - }, - "description": "Sample for UpdateClientTlsPolicy", - "file": "networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1alpha1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1alpha1_generated_network_security_update_client_tls_policy_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/scripts/fixup_network_security_v1alpha1_keywords.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/scripts/fixup_network_security_v1alpha1_keywords.py deleted file mode 100644 index f2a9d62fb02b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/scripts/fixup_network_security_v1alpha1_keywords.py +++ /dev/null @@ -1,180 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 network_securityCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_client_tls_policy': ('parent', 'client_tls_policy_id', 'client_tls_policy', ), - 'delete_client_tls_policy': ('name', ), - 'get_client_tls_policy': ('name', ), - 'list_client_tls_policies': ('parent', 'page_size', 'page_token', ), - 'update_client_tls_policy': ('client_tls_policy', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=network_securityCallTransformer(), -): - """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 network_security 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/google-cloud-network-security/v1alpha1/setup.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/setup.py deleted file mode 100644 index 1f618aa7ad2f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-network-security' - - -description = "Google Cloud Network Security API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/network_security/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0", - "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", - "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.14.0, <1.0.0", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.13.txt deleted file mode 100644 index 2010e549cceb..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.13.txt +++ /dev/null @@ -1,12 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -proto-plus>=1 -protobuf>=6 -grpc-google-iam-v1>=0 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.7.txt deleted file mode 100644 index 56affbd9bd75..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.14.0 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1alpha1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1alpha1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/test_network_security.py b/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/test_network_security.py deleted file mode 100644 index 3ac7a18a5f2f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1alpha1/tests/unit/gapic/network_security_v1alpha1/test_network_security.py +++ /dev/null @@ -1,7023 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.location import locations_pb2 -from google.cloud.network_security_v1alpha1.services.network_security import NetworkSecurityAsyncClient -from google.cloud.network_security_v1alpha1.services.network_security import NetworkSecurityClient -from google.cloud.network_security_v1alpha1.services.network_security import pagers -from google.cloud.network_security_v1alpha1.services.network_security import transports -from google.cloud.network_security_v1alpha1.types import client_tls_policy -from google.cloud.network_security_v1alpha1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1alpha1.types import common -from google.cloud.network_security_v1alpha1.types import tls -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# 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 - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -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 NetworkSecurityClient._get_default_mtls_endpoint(None) is None - assert NetworkSecurityClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert NetworkSecurityClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - NetworkSecurityClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - NetworkSecurityClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert NetworkSecurityClient._get_client_cert_source(None, False) is None - assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert NetworkSecurityClient._get_client_cert_source(None, True) is mock_default_cert_source - assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE - default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert NetworkSecurityClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - assert NetworkSecurityClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert NetworkSecurityClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert NetworkSecurityClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert NetworkSecurityClient._get_universe_domain(None, None) == NetworkSecurityClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - NetworkSecurityClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) -def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): - cred = mock.Mock(["get_cred_info"]) - cred.get_cred_info = mock.Mock(return_value=cred_info_json) - client = NetworkSecurityClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401,403,404,500]) -def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): - cred = mock.Mock([]) - assert not hasattr(cred, "get_cred_info") - client = NetworkSecurityClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -@pytest.mark.parametrize("client_class,transport_name", [ - (NetworkSecurityClient, "grpc"), - (NetworkSecurityAsyncClient, "grpc_asyncio"), - (NetworkSecurityClient, "rest"), -]) -def test_network_security_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networksecurity.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.NetworkSecurityGrpcTransport, "grpc"), - (transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.NetworkSecurityRestTransport, "rest"), -]) -def test_network_security_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (NetworkSecurityClient, "grpc"), - (NetworkSecurityAsyncClient, "grpc_asyncio"), - (NetworkSecurityClient, "rest"), -]) -def test_network_security_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networksecurity.googleapis.com' - ) - - -def test_network_security_client_get_transport_class(): - transport = NetworkSecurityClient.get_transport_class() - available_transports = [ - transports.NetworkSecurityGrpcTransport, - transports.NetworkSecurityRestTransport, - ] - assert transport in available_transports - - transport = NetworkSecurityClient.get_transport_class("grpc") - assert transport == transports.NetworkSecurityGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), - (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"), -]) -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -def test_network_security_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(NetworkSecurityClient, '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(NetworkSecurityClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "true"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "false"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", "true"), - (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", "false"), -]) -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_network_security_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - NetworkSecurityClient, NetworkSecurityAsyncClient -]) -@mock.patch.object(NetworkSecurityClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityAsyncClient)) -def test_network_security_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - NetworkSecurityClient, NetworkSecurityAsyncClient -]) -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -def test_network_security_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE - default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), - (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest"), -]) -def test_network_security_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (NetworkSecurityClient, transports.NetworkSecurityRestTransport, "rest", None), -]) -def test_network_security_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_network_security_client_client_options_from_dict(): - with mock.patch('google.cloud.network_security_v1alpha1.services.network_security.transports.NetworkSecurityGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = NetworkSecurityClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_network_security_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "networksecurity.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="networksecurity.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.ListClientTlsPoliciesRequest, - dict, -]) -def test_list_client_tls_policies(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = client_tls_policy.ListClientTlsPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClientTlsPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_client_tls_policies_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = client_tls_policy.ListClientTlsPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_client_tls_policies(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == client_tls_policy.ListClientTlsPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_client_tls_policies_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_client_tls_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_client_tls_policies] = mock_rpc - request = {} - client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_client_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_client_tls_policies in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_client_tls_policies] = mock_rpc - - request = {} - await client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_client_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.ListClientTlsPoliciesRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = client_tls_policy.ListClientTlsPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClientTlsPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async_from_dict(): - await test_list_client_tls_policies_async(request_type=dict) - -def test_list_client_tls_policies_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.ListClientTlsPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - client.list_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_client_tls_policies_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.ListClientTlsPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) - await client.list_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_client_tls_policies_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_client_tls_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_client_tls_policies_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policies( - client_tls_policy.ListClientTlsPoliciesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_client_tls_policies_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_client_tls_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_client_tls_policies_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_client_tls_policies( - client_tls_policy.ListClientTlsPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_client_tls_policies_pager(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_client_tls_policies(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) - for i in results) -def test_list_client_tls_policies_pages(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_client_tls_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_list_client_tls_policies_async_pager(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_client_tls_policies(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async_pages(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_client_tls_policies(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.GetClientTlsPolicyRequest, - dict, -]) -def test_get_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - ) - response = client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = client_tls_policy.GetClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, client_tls_policy.ClientTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.sni == 'sni_value' - - -def test_get_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = client_tls_policy.GetClientTlsPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == client_tls_policy.GetClientTlsPolicyRequest( - name='name_value', - ) - -def test_get_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_client_tls_policy] = mock_rpc - request = {} - client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_client_tls_policy] = mock_rpc - - request = {} - await client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.GetClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - )) - response = await client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = client_tls_policy.GetClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, client_tls_policy.ClientTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.sni == 'sni_value' - - -@pytest.mark.asyncio -async def test_get_client_tls_policy_async_from_dict(): - await test_get_client_tls_policy_async(request_type=dict) - -def test_get_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.GetClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value = client_tls_policy.ClientTlsPolicy() - client.get_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.GetClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) - await client.get_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ClientTlsPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - client_tls_policy.GetClientTlsPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ClientTlsPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_client_tls_policy( - client_tls_policy.GetClientTlsPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_client_tls_policy.CreateClientTlsPolicyRequest, - dict, -]) -def test_create_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest( - parent='parent_value', - client_tls_policy_id='client_tls_policy_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_client_tls_policy.CreateClientTlsPolicyRequest( - parent='parent_value', - client_tls_policy_id='client_tls_policy_id_value', - ) - -def test_create_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_client_tls_policy] = mock_rpc - request = {} - client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_client_tls_policy] = mock_rpc - - request = {} - await client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_client_tls_policy_async_from_dict(): - await test_create_client_tls_policy_async(request_type=dict) - -def test_create_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_client_tls_policy( - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].client_tls_policy_id - mock_val = 'client_tls_policy_id_value' - assert arg == mock_val - - -def test_create_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - gcn_client_tls_policy.CreateClientTlsPolicyRequest(), - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - -@pytest.mark.asyncio -async def test_create_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_client_tls_policy( - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].client_tls_policy_id - mock_val = 'client_tls_policy_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_client_tls_policy( - gcn_client_tls_policy.CreateClientTlsPolicyRequest(), - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_client_tls_policy.UpdateClientTlsPolicyRequest, - dict, -]) -def test_update_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_client_tls_policy.UpdateClientTlsPolicyRequest( - ) - -def test_update_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_client_tls_policy] = mock_rpc - request = {} - client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_client_tls_policy] = mock_rpc - - request = {} - await client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_client_tls_policy_async_from_dict(): - await test_update_client_tls_policy_async(request_type=dict) - -def test_update_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - request.client_tls_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_client_tls_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', - 'client_tls_policy.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - request.client_tls_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_client_tls_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', - 'client_tls_policy.name=name_value', - ) in kw['metadata'] - - -def test_update_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_client_tls_policy( - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_client_tls_policy( - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_client_tls_policy( - gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.DeleteClientTlsPolicyRequest, - dict, -]) -def test_delete_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = client_tls_policy.DeleteClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = client_tls_policy.DeleteClientTlsPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == client_tls_policy.DeleteClientTlsPolicyRequest( - name='name_value', - ) - -def test_delete_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_client_tls_policy] = mock_rpc - request = {} - client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_client_tls_policy] = mock_rpc - - request = {} - await client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.DeleteClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = client_tls_policy.DeleteClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_async_from_dict(): - await test_delete_client_tls_policy_async(request_type=dict) - -def test_delete_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.DeleteClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.DeleteClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - client_tls_policy.DeleteClientTlsPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_client_tls_policy( - client_tls_policy.DeleteClientTlsPolicyRequest(), - name='name_value', - ) - - -def test_list_client_tls_policies_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_client_tls_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_client_tls_policies] = mock_rpc - - request = {} - client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_client_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_client_tls_policies_rest_required_fields(request_type=client_tls_policy.ListClientTlsPoliciesRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_client_tls_policies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_client_tls_policies._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ListClientTlsPoliciesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_client_tls_policies(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_client_tls_policies_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_client_tls_policies._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_client_tls_policies_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ListClientTlsPoliciesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_client_tls_policies(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/clientTlsPolicies" % client.transport._host, args[1]) - - -def test_list_client_tls_policies_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_client_tls_policies( - client_tls_policy.ListClientTlsPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_client_tls_policies_rest_pager(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(client_tls_policy.ListClientTlsPoliciesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_client_tls_policies(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) - for i in results) - - pages = list(client.list_client_tls_policies(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_client_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_client_tls_policy] = mock_rpc - - request = {} - client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_client_tls_policy_rest_required_fields(request_type=client_tls_policy.GetClientTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ClientTlsPolicy() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_client_tls_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_client_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_client_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_client_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ClientTlsPolicy() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_client_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) - - -def test_get_client_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_client_tls_policy( - client_tls_policy.GetClientTlsPolicyRequest(), - name='name_value', - ) - - -def test_create_client_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_client_tls_policy] = mock_rpc - - request = {} - client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_client_tls_policy_rest_required_fields(request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["client_tls_policy_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "clientTlsPolicyId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "clientTlsPolicyId" in jsonified_request - assert jsonified_request["clientTlsPolicyId"] == request_init["client_tls_policy_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["clientTlsPolicyId"] = 'client_tls_policy_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_client_tls_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("client_tls_policy_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "clientTlsPolicyId" in jsonified_request - assert jsonified_request["clientTlsPolicyId"] == 'client_tls_policy_id_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_client_tls_policy(request) - - expected_params = [ - ( - "clientTlsPolicyId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_client_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_client_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("clientTlsPolicyId", )) & set(("parent", "clientTlsPolicyId", "clientTlsPolicy", ))) - - -def test_create_client_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_client_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha1/{parent=projects/*/locations/*}/clientTlsPolicies" % client.transport._host, args[1]) - - -def test_create_client_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_client_tls_policy( - gcn_client_tls_policy.CreateClientTlsPolicyRequest(), - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - -def test_update_client_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_client_tls_policy] = mock_rpc - - request = {} - client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_client_tls_policy_rest_required_fields(request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_client_tls_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.update_client_tls_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_client_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_client_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("clientTlsPolicy", ))) - - -def test_update_client_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_client_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha1/{client_tls_policy.name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) - - -def test_update_client_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_client_tls_policy( - gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_client_tls_policy_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_client_tls_policy] = mock_rpc - - request = {} - client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_client_tls_policy_rest_required_fields(request_type=client_tls_policy.DeleteClientTlsPolicyRequest): - transport_class = transports.NetworkSecurityRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_client_tls_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_client_tls_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_client_tls_policy_rest_unset_required_fields(): - transport = transports.NetworkSecurityRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_client_tls_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_client_tls_policy_rest_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_client_tls_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha1/{name=projects/*/locations/*/clientTlsPolicies/*}" % client.transport._host, args[1]) - - -def test_delete_client_tls_policy_rest_flattened_error(transport: str = 'rest'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_client_tls_policy( - client_tls_policy.DeleteClientTlsPolicyRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = NetworkSecurityClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.NetworkSecurityGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.NetworkSecurityGrpcTransport, - transports.NetworkSecurityGrpcAsyncIOTransport, - transports.NetworkSecurityRestTransport, -]) -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_kind_grpc(): - transport = NetworkSecurityClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_client_tls_policies_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - client.list_client_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.ListClientTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value = client_tls_policy.ClientTlsPolicy() - client.get_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.GetClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = NetworkSecurityAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_client_tls_policies_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - )) - await client.list_client_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.ListClientTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - )) - await client.get_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.GetClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = NetworkSecurityClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_client_tls_policies_rest_bad_request(request_type=client_tls_policy.ListClientTlsPoliciesRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_client_tls_policies(request) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.ListClientTlsPoliciesRequest, - dict, -]) -def test_list_client_tls_policies_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = client_tls_policy.ListClientTlsPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_client_tls_policies(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClientTlsPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_client_tls_policies_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_client_tls_policies") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_list_client_tls_policies_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_list_client_tls_policies") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = client_tls_policy.ListClientTlsPoliciesRequest.pb(client_tls_policy.ListClientTlsPoliciesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = client_tls_policy.ListClientTlsPoliciesResponse.to_json(client_tls_policy.ListClientTlsPoliciesResponse()) - req.return_value.content = return_value - - request = client_tls_policy.ListClientTlsPoliciesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - post_with_metadata.return_value = client_tls_policy.ListClientTlsPoliciesResponse(), metadata - - client.list_client_tls_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_client_tls_policy_rest_bad_request(request_type=client_tls_policy.GetClientTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_client_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.GetClientTlsPolicyRequest, - dict, -]) -def test_get_client_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = client_tls_policy.ClientTlsPolicy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_client_tls_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, client_tls_policy.ClientTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.sni == 'sni_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_client_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_client_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_get_client_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_get_client_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = client_tls_policy.GetClientTlsPolicyRequest.pb(client_tls_policy.GetClientTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = client_tls_policy.ClientTlsPolicy.to_json(client_tls_policy.ClientTlsPolicy()) - req.return_value.content = return_value - - request = client_tls_policy.GetClientTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = client_tls_policy.ClientTlsPolicy() - post_with_metadata.return_value = client_tls_policy.ClientTlsPolicy(), metadata - - client.get_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_client_tls_policy_rest_bad_request(request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_client_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - gcn_client_tls_policy.CreateClientTlsPolicyRequest, - dict, -]) -def test_create_client_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["client_tls_policy"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'sni': 'sni_value', 'client_certificate': {'local_filepath': {'certificate_path': 'certificate_path_value', 'private_key_path': 'private_key_path_value'}, 'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'server_validation_ca': [{'ca_cert_path': 'ca_cert_path_value', 'grpc_endpoint': {}, 'certificate_provider_instance': {}}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gcn_client_tls_policy.CreateClientTlsPolicyRequest.meta.fields["client_tls_policy"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["client_tls_policy"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["client_tls_policy"][field])): - del request_init["client_tls_policy"][field][i][subfield] - else: - del request_init["client_tls_policy"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_client_tls_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_client_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_client_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_create_client_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_create_client_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gcn_client_tls_policy.CreateClientTlsPolicyRequest.pb(gcn_client_tls_policy.CreateClientTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.create_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_client_tls_policy_rest_bad_request(request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_client_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - gcn_client_tls_policy.UpdateClientTlsPolicyRequest, - dict, -]) -def test_update_client_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'client_tls_policy': {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'}} - request_init["client_tls_policy"] = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'sni': 'sni_value', 'client_certificate': {'local_filepath': {'certificate_path': 'certificate_path_value', 'private_key_path': 'private_key_path_value'}, 'grpc_endpoint': {'target_uri': 'target_uri_value'}, 'certificate_provider_instance': {'plugin_instance': 'plugin_instance_value'}}, 'server_validation_ca': [{'ca_cert_path': 'ca_cert_path_value', 'grpc_endpoint': {}, 'certificate_provider_instance': {}}]} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.meta.fields["client_tls_policy"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["client_tls_policy"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["client_tls_policy"][field])): - del request_init["client_tls_policy"][field][i][subfield] - else: - del request_init["client_tls_policy"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_client_tls_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_client_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_client_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_update_client_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_update_client_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gcn_client_tls_policy.UpdateClientTlsPolicyRequest.pb(gcn_client_tls_policy.UpdateClientTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.update_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_client_tls_policy_rest_bad_request(request_type=client_tls_policy.DeleteClientTlsPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_client_tls_policy(request) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.DeleteClientTlsPolicyRequest, - dict, -]) -def test_delete_client_tls_policy_rest_call_success(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clientTlsPolicies/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_client_tls_policy(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_client_tls_policy_rest_interceptors(null_interceptor): - transport = transports.NetworkSecurityRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.NetworkSecurityRestInterceptor(), - ) - client = NetworkSecurityClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_client_tls_policy") as post, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "post_delete_client_tls_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.NetworkSecurityRestInterceptor, "pre_delete_client_tls_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = client_tls_policy.DeleteClientTlsPolicyRequest.pb(client_tls_policy.DeleteClientTlsPolicyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = client_tls_policy.DeleteClientTlsPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata - - client.delete_client_tls_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_initialize_client_w_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_client_tls_policies_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - client.list_client_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.ListClientTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_client_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - client.get_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.GetClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_client_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - client.create_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_client_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - client.update_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_client_tls_policy_empty_call_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - client.delete_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() - - assert args[0] == request_msg - - -def test_network_security_rest_lro_client(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have an api-core operations client. - assert isinstance( - transport.operations_client, -operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.NetworkSecurityGrpcTransport, - ) - -def test_network_security_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.NetworkSecurityTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_network_security_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.network_security_v1alpha1.services.network_security.transports.NetworkSecurityTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.NetworkSecurityTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_client_tls_policies', - 'get_client_tls_policy', - 'create_client_tls_policy', - 'update_client_tls_policy', - 'delete_client_tls_policy', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_network_security_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.network_security_v1alpha1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.NetworkSecurityTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_network_security_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.network_security_v1alpha1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.NetworkSecurityTransport() - adc.assert_called_once() - - -def test_network_security_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) - NetworkSecurityClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.NetworkSecurityGrpcTransport, - transports.NetworkSecurityGrpcAsyncIOTransport, - ], -) -def test_network_security_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.NetworkSecurityGrpcTransport, - transports.NetworkSecurityGrpcAsyncIOTransport, - transports.NetworkSecurityRestTransport, - ], -) -def test_network_security_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.NetworkSecurityGrpcTransport, grpc_helpers), - (transports.NetworkSecurityGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_network_security_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( - "networksecurity.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="networksecurity.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) -def test_network_security_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_network_security_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.NetworkSecurityRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_network_security_host_no_port(transport_name): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networksecurity.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_network_security_host_with_port(transport_name): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networksecurity.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networksecurity.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_network_security_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = NetworkSecurityClient( - credentials=creds1, - transport=transport_name, - ) - client2 = NetworkSecurityClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_client_tls_policies._session - session2 = client2.transport.list_client_tls_policies._session - assert session1 != session2 - session1 = client1.transport.get_client_tls_policy._session - session2 = client2.transport.get_client_tls_policy._session - assert session1 != session2 - session1 = client1.transport.create_client_tls_policy._session - session2 = client2.transport.create_client_tls_policy._session - assert session1 != session2 - session1 = client1.transport.update_client_tls_policy._session - session2 = client2.transport.update_client_tls_policy._session - assert session1 != session2 - session1 = client1.transport.delete_client_tls_policy._session - session2 = client2.transport.delete_client_tls_policy._session - assert session1 != session2 -def test_network_security_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.NetworkSecurityGrpcTransport( - 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_network_security_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.NetworkSecurityGrpcAsyncIOTransport( - 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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) -def test_network_security_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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) -def test_network_security_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_network_security_grpc_lro_client(): - client = NetworkSecurityClient( - 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_network_security_grpc_lro_async_client(): - client = NetworkSecurityAsyncClient( - 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_client_tls_policy_path(): - project = "squid" - location = "clam" - client_tls_policy = "whelk" - expected = "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) - actual = NetworkSecurityClient.client_tls_policy_path(project, location, client_tls_policy) - assert expected == actual - - -def test_parse_client_tls_policy_path(): - expected = { - "project": "octopus", - "location": "oyster", - "client_tls_policy": "nudibranch", - } - path = NetworkSecurityClient.client_tls_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_client_tls_policy_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = NetworkSecurityClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = NetworkSecurityClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = NetworkSecurityClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = NetworkSecurityClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = NetworkSecurityClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = NetworkSecurityClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = NetworkSecurityClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = NetworkSecurityClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = NetworkSecurityClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = NetworkSecurityClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: - transport_class = NetworkSecurityClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_delete_operation(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None - - client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_delete_operation_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_delete_operation_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/.coveragerc b/owl-bot-staging/google-cloud-network-security/v1beta1/.coveragerc deleted file mode 100644 index ed01d62f0f9a..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/network_security/__init__.py - google/cloud/network_security/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/.flake8 b/owl-bot-staging/google-cloud-network-security/v1beta1/.flake8 deleted file mode 100644 index 90316de21489..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/.flake8 +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -[flake8] -# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): -# Resolve flake8 lint issues -ignore = E203, E231, E266, E501, W503 -exclude = - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): - # Ensure that generated code passes flake8 lint - **/gapic/** - **/services/** - **/types/** - # Exclude Protobuf gencode - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/LICENSE b/owl-bot-staging/google-cloud-network-security/v1beta1/LICENSE deleted file mode 100644 index d64569567334..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/google-cloud-network-security/v1beta1/MANIFEST.in b/owl-bot-staging/google-cloud-network-security/v1beta1/MANIFEST.in deleted file mode 100644 index dae249ec8976..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/MANIFEST.in +++ /dev/null @@ -1,20 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -include README.rst LICENSE -recursive-include google *.py *.pyi *.json *.proto py.typed -recursive-include tests * -global-exclude *.py[co] -global-exclude __pycache__ diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/README.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/README.rst deleted file mode 100644 index fed4f0a4d3c6..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Cloud Network Security 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 Network Security 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 - - -Logging -------- - -This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. -Note the following: - -#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. -#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. -#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. - - -Simple, environment-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google -logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged -messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging -event. - -A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. - -- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. -- Invalid logging scopes: :code:`foo`, :code:`123`, etc. - -**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. - - -Examples -^^^^^^^^ - -- Enabling the default handler for all Google-based loggers - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google - -- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 - - -Advanced, code-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can also configure a valid logging scope using Python's standard `logging` mechanism. - - -Examples -^^^^^^^^ - -- Configuring a handler for all Google-based loggers - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - -- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google.cloud.library_v1") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - - -Logging details -~~~~~~~~~~~~~~~ - -#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root - logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set - :code:`logging.getLogger("google").propagate = True` in your code. -#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for - one library, but decide you need to also set up environment-based logging configuration for another library. - - #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual - if the code -based configuration gets applied first. - -#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get - executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. - (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_static/custom.css b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_static/custom.css deleted file mode 100644 index b0a295464b23..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_static/custom.css +++ /dev/null @@ -1,20 +0,0 @@ -div#python2-eol { - border-color: red; - border-width: medium; -} - -/* Ensure minimum width for 'Parameters' / 'Returns' column */ -dl.field-list > dt { - min-width: 100px -} - -/* Insert space between methods for readability */ -dl.method { - padding-top: 10px; - padding-bottom: 10px -} - -/* Insert empty space between classes */ -dl.class { - padding-bottom: 50px -} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_templates/layout.html b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_templates/layout.html deleted file mode 100644 index 95e9c77fcfe1..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/_templates/layout.html +++ /dev/null @@ -1,50 +0,0 @@ - -{% extends "!layout.html" %} -{%- block content %} -{%- if theme_fixed_sidebar|lower == 'true' %} -
- {{ sidebar() }} - {%- block document %} -
- {%- if render_sidebar %} -
- {%- endif %} - - {%- block relbar_top %} - {%- if theme_show_relbar_top|tobool %} - - {%- endif %} - {% endblock %} - -
-
- As of January 1, 2020 this library no longer supports Python 2 on the latest released version. - Library versions released prior to that date will continue to be available. For more information please - visit Python 2 support on Google Cloud. -
- {% block body %} {% endblock %} -
- - {%- block relbar_bottom %} - {%- if theme_show_relbar_bottom|tobool %} - - {%- endif %} - {% endblock %} - - {%- if render_sidebar %} -
- {%- endif %} -
- {%- endblock %} -
-
-{%- else %} -{{ super() }} -{%- endif %} -{%- endblock %} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/conf.py b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/conf.py deleted file mode 100644 index cf26b0443b74..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/conf.py +++ /dev/null @@ -1,385 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-network-security 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("..")) - -# For plugins that can not read conf.py. -# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 -sys.path.insert(0, os.path.abspath(".")) - -__version__ = "" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.5.0" - -# 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.doctest", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", - "recommonmark", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_options = {"members": True} -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# source_suffix = ['.rst', '.md'] -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-network-security" -copyright = u"2025, Google, LLC" -author = u"Google APIs" - -# 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", - "**/.nox/**/*", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/README.rst", -] - -# 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 google-cloud-network-security", - "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-network-security-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-network-security.tex", - u"google-cloud-network-security Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-network-security", - "google-cloud-network-security Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-network-security", - "google-cloud-network-security Documentation", - author, - "google-cloud-network-security", - "google-cloud-network-security Library", - "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": ("https://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), - "google.api_core": ( - "https://googleapis.dev/python/google-api-core/latest/", - None, - ), - "grpc": ("https://grpc.github.io/grpc/python/", None), - "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", 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/google-cloud-network-security/v1beta1/docs/index.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/index.rst deleted file mode 100644 index 887a96a98d64..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. include:: multiprocessing.rst - - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - network_security_v1beta1/services_ - network_security_v1beta1/types_ diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/multiprocessing.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/multiprocessing.rst deleted file mode 100644 index 536d17b2ea65..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/multiprocessing.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. note:: - - Because this client uses :mod:`grpc` library, it is safe to - share instances across threads. In multiprocessing scenarios, the best - practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.pool.Pool` or - :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/network_security.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/network_security.rst deleted file mode 100644 index d410f02fae7f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/network_security.rst +++ /dev/null @@ -1,10 +0,0 @@ -NetworkSecurity ---------------------------------- - -.. automodule:: google.cloud.network_security_v1beta1.services.network_security - :members: - :inherited-members: - -.. automodule:: google.cloud.network_security_v1beta1.services.network_security.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/services_.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/services_.rst deleted file mode 100644 index dd4dc6164423..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Network Security v1beta1 API -====================================================== -.. toctree:: - :maxdepth: 2 - - network_security diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/types_.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/types_.rst deleted file mode 100644 index a51fb755cd14..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/docs/network_security_v1beta1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Network Security v1beta1 API -=================================================== - -.. automodule:: google.cloud.network_security_v1beta1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/__init__.py deleted file mode 100644 index 69ca4223fb8a..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/__init__.py +++ /dev/null @@ -1,79 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.network_security import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.network_security_v1beta1.services.network_security.client import NetworkSecurityClient -from google.cloud.network_security_v1beta1.services.network_security.async_client import NetworkSecurityAsyncClient - -from google.cloud.network_security_v1beta1.types.authorization_policy import AuthorizationPolicy -from google.cloud.network_security_v1beta1.types.authorization_policy import CreateAuthorizationPolicyRequest -from google.cloud.network_security_v1beta1.types.authorization_policy import DeleteAuthorizationPolicyRequest -from google.cloud.network_security_v1beta1.types.authorization_policy import GetAuthorizationPolicyRequest -from google.cloud.network_security_v1beta1.types.authorization_policy import ListAuthorizationPoliciesRequest -from google.cloud.network_security_v1beta1.types.authorization_policy import ListAuthorizationPoliciesResponse -from google.cloud.network_security_v1beta1.types.authorization_policy import UpdateAuthorizationPolicyRequest -from google.cloud.network_security_v1beta1.types.client_tls_policy import ClientTlsPolicy -from google.cloud.network_security_v1beta1.types.client_tls_policy import CreateClientTlsPolicyRequest -from google.cloud.network_security_v1beta1.types.client_tls_policy import DeleteClientTlsPolicyRequest -from google.cloud.network_security_v1beta1.types.client_tls_policy import GetClientTlsPolicyRequest -from google.cloud.network_security_v1beta1.types.client_tls_policy import ListClientTlsPoliciesRequest -from google.cloud.network_security_v1beta1.types.client_tls_policy import ListClientTlsPoliciesResponse -from google.cloud.network_security_v1beta1.types.client_tls_policy import UpdateClientTlsPolicyRequest -from google.cloud.network_security_v1beta1.types.common import OperationMetadata -from google.cloud.network_security_v1beta1.types.server_tls_policy import CreateServerTlsPolicyRequest -from google.cloud.network_security_v1beta1.types.server_tls_policy import DeleteServerTlsPolicyRequest -from google.cloud.network_security_v1beta1.types.server_tls_policy import GetServerTlsPolicyRequest -from google.cloud.network_security_v1beta1.types.server_tls_policy import ListServerTlsPoliciesRequest -from google.cloud.network_security_v1beta1.types.server_tls_policy import ListServerTlsPoliciesResponse -from google.cloud.network_security_v1beta1.types.server_tls_policy import ServerTlsPolicy -from google.cloud.network_security_v1beta1.types.server_tls_policy import UpdateServerTlsPolicyRequest -from google.cloud.network_security_v1beta1.types.tls import CertificateProvider -from google.cloud.network_security_v1beta1.types.tls import CertificateProviderInstance -from google.cloud.network_security_v1beta1.types.tls import GrpcEndpoint -from google.cloud.network_security_v1beta1.types.tls import ValidationCA - -__all__ = ('NetworkSecurityClient', - 'NetworkSecurityAsyncClient', - 'AuthorizationPolicy', - 'CreateAuthorizationPolicyRequest', - 'DeleteAuthorizationPolicyRequest', - 'GetAuthorizationPolicyRequest', - 'ListAuthorizationPoliciesRequest', - 'ListAuthorizationPoliciesResponse', - 'UpdateAuthorizationPolicyRequest', - 'ClientTlsPolicy', - 'CreateClientTlsPolicyRequest', - 'DeleteClientTlsPolicyRequest', - 'GetClientTlsPolicyRequest', - 'ListClientTlsPoliciesRequest', - 'ListClientTlsPoliciesResponse', - 'UpdateClientTlsPolicyRequest', - 'OperationMetadata', - 'CreateServerTlsPolicyRequest', - 'DeleteServerTlsPolicyRequest', - 'GetServerTlsPolicyRequest', - 'ListServerTlsPoliciesRequest', - 'ListServerTlsPoliciesResponse', - 'ServerTlsPolicy', - 'UpdateServerTlsPolicyRequest', - 'CertificateProvider', - 'CertificateProviderInstance', - 'GrpcEndpoint', - 'ValidationCA', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/py.typed b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/py.typed deleted file mode 100644 index 41b3c3019247..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/__init__.py deleted file mode 100644 index 095f44249d17..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.network_security_v1beta1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.network_security import NetworkSecurityClient -from .services.network_security import NetworkSecurityAsyncClient - -from .types.authorization_policy import AuthorizationPolicy -from .types.authorization_policy import CreateAuthorizationPolicyRequest -from .types.authorization_policy import DeleteAuthorizationPolicyRequest -from .types.authorization_policy import GetAuthorizationPolicyRequest -from .types.authorization_policy import ListAuthorizationPoliciesRequest -from .types.authorization_policy import ListAuthorizationPoliciesResponse -from .types.authorization_policy import UpdateAuthorizationPolicyRequest -from .types.client_tls_policy import ClientTlsPolicy -from .types.client_tls_policy import CreateClientTlsPolicyRequest -from .types.client_tls_policy import DeleteClientTlsPolicyRequest -from .types.client_tls_policy import GetClientTlsPolicyRequest -from .types.client_tls_policy import ListClientTlsPoliciesRequest -from .types.client_tls_policy import ListClientTlsPoliciesResponse -from .types.client_tls_policy import UpdateClientTlsPolicyRequest -from .types.common import OperationMetadata -from .types.server_tls_policy import CreateServerTlsPolicyRequest -from .types.server_tls_policy import DeleteServerTlsPolicyRequest -from .types.server_tls_policy import GetServerTlsPolicyRequest -from .types.server_tls_policy import ListServerTlsPoliciesRequest -from .types.server_tls_policy import ListServerTlsPoliciesResponse -from .types.server_tls_policy import ServerTlsPolicy -from .types.server_tls_policy import UpdateServerTlsPolicyRequest -from .types.tls import CertificateProvider -from .types.tls import CertificateProviderInstance -from .types.tls import GrpcEndpoint -from .types.tls import ValidationCA - -__all__ = ( - 'NetworkSecurityAsyncClient', -'AuthorizationPolicy', -'CertificateProvider', -'CertificateProviderInstance', -'ClientTlsPolicy', -'CreateAuthorizationPolicyRequest', -'CreateClientTlsPolicyRequest', -'CreateServerTlsPolicyRequest', -'DeleteAuthorizationPolicyRequest', -'DeleteClientTlsPolicyRequest', -'DeleteServerTlsPolicyRequest', -'GetAuthorizationPolicyRequest', -'GetClientTlsPolicyRequest', -'GetServerTlsPolicyRequest', -'GrpcEndpoint', -'ListAuthorizationPoliciesRequest', -'ListAuthorizationPoliciesResponse', -'ListClientTlsPoliciesRequest', -'ListClientTlsPoliciesResponse', -'ListServerTlsPoliciesRequest', -'ListServerTlsPoliciesResponse', -'NetworkSecurityClient', -'OperationMetadata', -'ServerTlsPolicy', -'UpdateAuthorizationPolicyRequest', -'UpdateClientTlsPolicyRequest', -'UpdateServerTlsPolicyRequest', -'ValidationCA', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_metadata.json b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_metadata.json deleted file mode 100644 index 8bf9dacdd358..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,173 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.network_security_v1beta1", - "protoPackage": "google.cloud.networksecurity.v1beta1", - "schema": "1.0", - "services": { - "NetworkSecurity": { - "clients": { - "grpc": { - "libraryClient": "NetworkSecurityClient", - "rpcs": { - "CreateAuthorizationPolicy": { - "methods": [ - "create_authorization_policy" - ] - }, - "CreateClientTlsPolicy": { - "methods": [ - "create_client_tls_policy" - ] - }, - "CreateServerTlsPolicy": { - "methods": [ - "create_server_tls_policy" - ] - }, - "DeleteAuthorizationPolicy": { - "methods": [ - "delete_authorization_policy" - ] - }, - "DeleteClientTlsPolicy": { - "methods": [ - "delete_client_tls_policy" - ] - }, - "DeleteServerTlsPolicy": { - "methods": [ - "delete_server_tls_policy" - ] - }, - "GetAuthorizationPolicy": { - "methods": [ - "get_authorization_policy" - ] - }, - "GetClientTlsPolicy": { - "methods": [ - "get_client_tls_policy" - ] - }, - "GetServerTlsPolicy": { - "methods": [ - "get_server_tls_policy" - ] - }, - "ListAuthorizationPolicies": { - "methods": [ - "list_authorization_policies" - ] - }, - "ListClientTlsPolicies": { - "methods": [ - "list_client_tls_policies" - ] - }, - "ListServerTlsPolicies": { - "methods": [ - "list_server_tls_policies" - ] - }, - "UpdateAuthorizationPolicy": { - "methods": [ - "update_authorization_policy" - ] - }, - "UpdateClientTlsPolicy": { - "methods": [ - "update_client_tls_policy" - ] - }, - "UpdateServerTlsPolicy": { - "methods": [ - "update_server_tls_policy" - ] - } - } - }, - "grpc-async": { - "libraryClient": "NetworkSecurityAsyncClient", - "rpcs": { - "CreateAuthorizationPolicy": { - "methods": [ - "create_authorization_policy" - ] - }, - "CreateClientTlsPolicy": { - "methods": [ - "create_client_tls_policy" - ] - }, - "CreateServerTlsPolicy": { - "methods": [ - "create_server_tls_policy" - ] - }, - "DeleteAuthorizationPolicy": { - "methods": [ - "delete_authorization_policy" - ] - }, - "DeleteClientTlsPolicy": { - "methods": [ - "delete_client_tls_policy" - ] - }, - "DeleteServerTlsPolicy": { - "methods": [ - "delete_server_tls_policy" - ] - }, - "GetAuthorizationPolicy": { - "methods": [ - "get_authorization_policy" - ] - }, - "GetClientTlsPolicy": { - "methods": [ - "get_client_tls_policy" - ] - }, - "GetServerTlsPolicy": { - "methods": [ - "get_server_tls_policy" - ] - }, - "ListAuthorizationPolicies": { - "methods": [ - "list_authorization_policies" - ] - }, - "ListClientTlsPolicies": { - "methods": [ - "list_client_tls_policies" - ] - }, - "ListServerTlsPolicies": { - "methods": [ - "list_server_tls_policies" - ] - }, - "UpdateAuthorizationPolicy": { - "methods": [ - "update_authorization_policy" - ] - }, - "UpdateClientTlsPolicy": { - "methods": [ - "update_client_tls_policy" - ] - }, - "UpdateServerTlsPolicy": { - "methods": [ - "update_server_tls_policy" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_version.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/py.typed b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/py.typed deleted file mode 100644 index 41b3c3019247..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-network-security package uses inline types. diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/__init__.py deleted file mode 100644 index cbf94b283c70..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/__init__.py deleted file mode 100644 index cddb3cfba9e6..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 NetworkSecurityClient -from .async_client import NetworkSecurityAsyncClient - -__all__ = ( - 'NetworkSecurityClient', - 'NetworkSecurityAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/async_client.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/async_client.py deleted file mode 100644 index 7098e6dca664..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/async_client.py +++ /dev/null @@ -1,2866 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.network_security_v1beta1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1beta1.services.network_security import pagers -from google.cloud.network_security_v1beta1.types import authorization_policy -from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1beta1.types import common -from google.cloud.network_security_v1beta1.types import server_tls_policy -from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy -from google.cloud.network_security_v1beta1.types import tls -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport -from .client import NetworkSecurityClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class NetworkSecurityAsyncClient: - """Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - """ - - _client: NetworkSecurityClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = NetworkSecurityClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = NetworkSecurityClient._DEFAULT_UNIVERSE - - authorization_policy_path = staticmethod(NetworkSecurityClient.authorization_policy_path) - parse_authorization_policy_path = staticmethod(NetworkSecurityClient.parse_authorization_policy_path) - client_tls_policy_path = staticmethod(NetworkSecurityClient.client_tls_policy_path) - parse_client_tls_policy_path = staticmethod(NetworkSecurityClient.parse_client_tls_policy_path) - server_tls_policy_path = staticmethod(NetworkSecurityClient.server_tls_policy_path) - parse_server_tls_policy_path = staticmethod(NetworkSecurityClient.parse_server_tls_policy_path) - common_billing_account_path = staticmethod(NetworkSecurityClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(NetworkSecurityClient.parse_common_billing_account_path) - common_folder_path = staticmethod(NetworkSecurityClient.common_folder_path) - parse_common_folder_path = staticmethod(NetworkSecurityClient.parse_common_folder_path) - common_organization_path = staticmethod(NetworkSecurityClient.common_organization_path) - parse_common_organization_path = staticmethod(NetworkSecurityClient.parse_common_organization_path) - common_project_path = staticmethod(NetworkSecurityClient.common_project_path) - parse_common_project_path = staticmethod(NetworkSecurityClient.parse_common_project_path) - common_location_path = staticmethod(NetworkSecurityClient.common_location_path) - parse_common_location_path = staticmethod(NetworkSecurityClient.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: - NetworkSecurityAsyncClient: The constructed client. - """ - return NetworkSecurityClient.from_service_account_info.__func__(NetworkSecurityAsyncClient, 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: - NetworkSecurityAsyncClient: The constructed client. - """ - return NetworkSecurityClient.from_service_account_file.__func__(NetworkSecurityAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return NetworkSecurityClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> NetworkSecurityTransport: - """Returns the transport used by the client instance. - - Returns: - NetworkSecurityTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = NetworkSecurityClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the network security async 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the NetworkSecurityTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client = NetworkSecurityClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.networksecurity_v1beta1.NetworkSecurityAsyncClient`.", - extra = { - "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "credentialsType": None, - } - ) - - async def list_authorization_policies(self, - request: Optional[Union[authorization_policy.ListAuthorizationPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAuthorizationPoliciesAsyncPager: - r"""Lists AuthorizationPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_list_authorization_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListAuthorizationPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_authorization_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest, dict]]): - The request object. Request used with the - ListAuthorizationPolicies method. - parent (:class:`str`): - Required. The project and location from which the - AuthorizationPolicies should be listed, specified in the - format ``projects/{project}/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager: - Response returned by the - ListAuthorizationPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.ListAuthorizationPoliciesRequest): - request = authorization_policy.ListAuthorizationPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_authorization_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.ListAuthorizationPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_authorization_policy(self, - request: Optional[Union[authorization_policy.GetAuthorizationPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> authorization_policy.AuthorizationPolicy: - r"""Gets details of a single AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_get_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_authorization_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.GetAuthorizationPolicyRequest, dict]]): - The request object. Request used by the - GetAuthorizationPolicy method. - name (:class:`str`): - Required. A name of the AuthorizationPolicy to get. Must - be in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.types.AuthorizationPolicy: - AuthorizationPolicy is a resource - that specifies how a server should - authorize incoming connections. This - resource in itself does not change the - configuration unless it's attached to a - target https proxy or endpoint config - selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.GetAuthorizationPolicyRequest): - request = authorization_policy.GetAuthorizationPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_authorization_policy(self, - request: Optional[Union[gcn_authorization_policy.CreateAuthorizationPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, - authorization_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new AuthorizationPolicy in a given project - and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_create_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1beta1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1beta1.CreateAuthorizationPolicyRequest( - parent="parent_value", - authorization_policy_id="authorization_policy_id_value", - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.create_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.CreateAuthorizationPolicyRequest, dict]]): - The request object. Request used by the - CreateAuthorizationPolicy method. - parent (:class:`str`): - Required. The parent resource of the - AuthorizationPolicy. Must be in the format - ``projects/{project}/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - authorization_policy (:class:`google.cloud.network_security_v1beta1.types.AuthorizationPolicy`): - Required. AuthorizationPolicy - resource to be created. - - This corresponds to the ``authorization_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - authorization_policy_id (:class:`str`): - Required. Short name of the AuthorizationPolicy resource - to be created. This value should be 1-63 characters - long, containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "authz_policy". - - This corresponds to the ``authorization_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1beta1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server - should authorize incoming connections. This resource - in itself does not change the configuration unless - it's attached to a target https proxy or endpoint - config selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, authorization_policy, authorization_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_authorization_policy.CreateAuthorizationPolicyRequest): - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if authorization_policy is not None: - request.authorization_policy = authorization_policy - if authorization_policy_id is not None: - request.authorization_policy_id = authorization_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_authorization_policy.AuthorizationPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_authorization_policy(self, - request: Optional[Union[gcn_authorization_policy.UpdateAuthorizationPolicyRequest, dict]] = None, - *, - authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single - AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_update_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1beta1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1beta1.UpdateAuthorizationPolicyRequest( - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.update_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.UpdateAuthorizationPolicyRequest, dict]]): - The request object. Request used by the - UpdateAuthorizationPolicy method. - authorization_policy (:class:`google.cloud.network_security_v1beta1.types.AuthorizationPolicy`): - Required. Updated AuthorizationPolicy - resource. - - This corresponds to the ``authorization_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Field mask is used to specify the fields to be - overwritten in the AuthorizationPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1beta1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server - should authorize incoming connections. This resource - in itself does not change the configuration unless - it's attached to a target https proxy or endpoint - config selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [authorization_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_authorization_policy.UpdateAuthorizationPolicyRequest): - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if authorization_policy is not None: - request.authorization_policy = authorization_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_authorization_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("authorization_policy.name", request.authorization_policy.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_authorization_policy.AuthorizationPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_authorization_policy(self, - request: Optional[Union[authorization_policy.DeleteAuthorizationPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_delete_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.DeleteAuthorizationPolicyRequest, dict]]): - The request object. Request used by the - DeleteAuthorizationPolicy method. - name (:class:`str`): - Required. A name of the AuthorizationPolicy to delete. - Must be in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.DeleteAuthorizationPolicyRequest): - request = authorization_policy.DeleteAuthorizationPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_server_tls_policies(self, - request: Optional[Union[server_tls_policy.ListServerTlsPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListServerTlsPoliciesAsyncPager: - r"""Lists ServerTlsPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_list_server_tls_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListServerTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_server_tls_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest, dict]]): - The request object. Request used by the - ListServerTlsPolicies method. - parent (:class:`str`): - Required. The project and location from which the - ServerTlsPolicies should be listed, specified in the - format ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager: - Response returned by the - ListServerTlsPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.ListServerTlsPoliciesRequest): - request = server_tls_policy.ListServerTlsPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_server_tls_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.ListServerTlsPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_server_tls_policy(self, - request: Optional[Union[server_tls_policy.GetServerTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> server_tls_policy.ServerTlsPolicy: - r"""Gets details of a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_get_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_server_tls_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.GetServerTlsPolicyRequest, dict]]): - The request object. Request used by the - GetServerTlsPolicy method. - name (:class:`str`): - Required. A name of the ServerTlsPolicy to get. Must be - in the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.types.ServerTlsPolicy: - ServerTlsPolicy is a resource that - specifies how a server should - authenticate incoming requests. This - resource itself does not affect - configuration unless it is attached to a - target https proxy or endpoint config - selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.GetServerTlsPolicyRequest): - request = server_tls_policy.GetServerTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_server_tls_policy(self, - request: Optional[Union[gcn_server_tls_policy.CreateServerTlsPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, - server_tls_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new ServerTlsPolicy in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_create_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1beta1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1beta1.CreateServerTlsPolicyRequest( - parent="parent_value", - server_tls_policy_id="server_tls_policy_id_value", - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.create_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.CreateServerTlsPolicyRequest, dict]]): - The request object. Request used by the - CreateServerTlsPolicy method. - parent (:class:`str`): - Required. The parent resource of the ServerTlsPolicy. - Must be in the format - ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - server_tls_policy (:class:`google.cloud.network_security_v1beta1.types.ServerTlsPolicy`): - Required. ServerTlsPolicy resource to - be created. - - This corresponds to the ``server_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - server_tls_policy_id (:class:`str`): - Required. Short name of the ServerTlsPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "server_mtls_policy". - - This corresponds to the ``server_tls_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1beta1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate - incoming requests. This resource itself does not - affect configuration unless it is attached to a - target https proxy or endpoint config selector - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, server_tls_policy, server_tls_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_server_tls_policy.CreateServerTlsPolicyRequest): - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if server_tls_policy is not None: - request.server_tls_policy = server_tls_policy - if server_tls_policy_id is not None: - request.server_tls_policy_id = server_tls_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_server_tls_policy.ServerTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_server_tls_policy(self, - request: Optional[Union[gcn_server_tls_policy.UpdateServerTlsPolicyRequest, dict]] = None, - *, - server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_update_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1beta1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1beta1.UpdateServerTlsPolicyRequest( - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.update_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.UpdateServerTlsPolicyRequest, dict]]): - The request object. Request used by UpdateServerTlsPolicy - method. - server_tls_policy (:class:`google.cloud.network_security_v1beta1.types.ServerTlsPolicy`): - Required. Updated ServerTlsPolicy - resource. - - This corresponds to the ``server_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Field mask is used to specify the fields to be - overwritten in the ServerTlsPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1beta1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate - incoming requests. This resource itself does not - affect configuration unless it is attached to a - target https proxy or endpoint config selector - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [server_tls_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_server_tls_policy.UpdateServerTlsPolicyRequest): - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if server_tls_policy is not None: - request.server_tls_policy = server_tls_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_server_tls_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("server_tls_policy.name", request.server_tls_policy.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_server_tls_policy.ServerTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_server_tls_policy(self, - request: Optional[Union[server_tls_policy.DeleteServerTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_delete_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.DeleteServerTlsPolicyRequest, dict]]): - The request object. Request used by the - DeleteServerTlsPolicy method. - name (:class:`str`): - Required. A name of the ServerTlsPolicy to delete. Must - be in the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.DeleteServerTlsPolicyRequest): - request = server_tls_policy.DeleteServerTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_client_tls_policies(self, - request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListClientTlsPoliciesAsyncPager: - r"""Lists ClientTlsPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest, dict]]): - The request object. Request used by the - ListClientTlsPolicies method. - parent (:class:`str`): - Required. The project and location from which the - ClientTlsPolicies should be listed, specified in the - format ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager: - Response returned by the - ListClientTlsPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): - request = client_tls_policy.ListClientTlsPoliciesRequest(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._client._transport._wrapped_methods[self._client._transport.list_client_tls_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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.ListClientTlsPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_client_tls_policy(self, - request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> client_tls_policy.ClientTlsPolicy: - r"""Gets details of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.GetClientTlsPolicyRequest, dict]]): - The request object. Request used by the - GetClientTlsPolicy method. - name (:class:`str`): - Required. A name of the ClientTlsPolicy to get. Must be - in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.types.ClientTlsPolicy: - ClientTlsPolicy is a resource that - specifies how a client should - authenticate connections to backends of - a service. This resource itself does not - affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): - request = client_tls_policy.GetClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.get_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - client_tls_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new ClientTlsPolicy in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1beta1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1beta1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.CreateClientTlsPolicyRequest, dict]]): - The request object. Request used by the - CreateClientTlsPolicy method. - parent (:class:`str`): - Required. The parent resource of the ClientTlsPolicy. - Must be in the format - ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy (:class:`google.cloud.network_security_v1beta1.types.ClientTlsPolicy`): - Required. ClientTlsPolicy resource to - be created. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy_id (:class:`str`): - Required. Short name of the ClientTlsPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "client_mtls_policy". - - This corresponds to the ``client_tls_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1beta1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, client_tls_policy, client_tls_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if client_tls_policy_id is not None: - request.client_tls_policy_id = client_tls_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, - *, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1beta1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1beta1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.UpdateClientTlsPolicyRequest, dict]]): - The request object. Request used by UpdateClientTlsPolicy - method. - client_tls_policy (:class:`google.cloud.network_security_v1beta1.types.ClientTlsPolicy`): - Required. Updated ClientTlsPolicy - resource. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. Field mask is used to specify the fields to be - overwritten in the ClientTlsPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - 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.network_security_v1beta1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [client_tls_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_client_tls_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("client_tls_policy.name", request.client_tls_policy.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_client_tls_policy(self, - request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - async def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.network_security_v1beta1.types.DeleteClientTlsPolicyRequest, dict]]): - The request object. Request used by the - DeleteClientTlsPolicy method. - name (:class:`str`): - Required. A name of the ClientTlsPolicy to delete. Must - be in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): - request = client_tls_policy.DeleteClientTlsPolicyRequest(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._client._transport._wrapped_methods[self._client._transport.delete_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_operations] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_location] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_locations] - - # 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),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "NetworkSecurityAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -__all__ = ( - "NetworkSecurityAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/client.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/client.py deleted file mode 100644 index f5b1f5318f5c..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/client.py +++ /dev/null @@ -1,3251 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 http import HTTPStatus -import json -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.network_security_v1beta1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1beta1.services.network_security import pagers -from google.cloud.network_security_v1beta1.types import authorization_policy -from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1beta1.types import common -from google.cloud.network_security_v1beta1.types import server_tls_policy -from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy -from google.cloud.network_security_v1beta1.types import tls -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import NetworkSecurityGrpcTransport -from .transports.grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport - - -class NetworkSecurityClientMeta(type): - """Metaclass for the NetworkSecurity 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[NetworkSecurityTransport]] - _transport_registry["grpc"] = NetworkSecurityGrpcTransport - _transport_registry["grpc_asyncio"] = NetworkSecurityGrpcAsyncIOTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[NetworkSecurityTransport]: - """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 NetworkSecurityClient(metaclass=NetworkSecurityClientMeta): - """Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - """ - - @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") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "networksecurity.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "networksecurity.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @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: - NetworkSecurityClient: 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: - NetworkSecurityClient: 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) -> NetworkSecurityTransport: - """Returns the transport used by the client instance. - - Returns: - NetworkSecurityTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def authorization_policy_path(project: str,location: str,authorization_policy: str,) -> str: - """Returns a fully-qualified authorization_policy string.""" - return "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format(project=project, location=location, authorization_policy=authorization_policy, ) - - @staticmethod - def parse_authorization_policy_path(path: str) -> Dict[str,str]: - """Parses a authorization_policy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/authorizationPolicies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def client_tls_policy_path(project: str,location: str,client_tls_policy: str,) -> str: - """Returns a fully-qualified client_tls_policy string.""" - return "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) - - @staticmethod - def parse_client_tls_policy_path(path: str) -> Dict[str,str]: - """Parses a client_tls_policy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clientTlsPolicies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def server_tls_policy_path(project: str,location: str,server_tls_policy: str,) -> str: - """Returns a fully-qualified server_tls_policy string.""" - return "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format(project=project, location=location, server_tls_policy=server_tls_policy, ) - - @staticmethod - def parse_server_tls_policy_path(path: str) -> Dict[str,str]: - """Parses a server_tls_policy path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/serverTlsPolicies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = NetworkSecurityClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError - ) -> None: - """Adds credential info string to error details for 401/403/404 errors. - - Args: - error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. - """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: - return - - cred = self._transport._credentials - - # get_cred_info is only available in google-auth>=2.35.0 - if not hasattr(cred, "get_cred_info"): - return - - # ignore the type check since pypy test fails when get_cred_info - # is not available - cred_info = cred.get_cred_info() # type: ignore - if cred_info and hasattr(error._details, "append"): - error._details.append(json.dumps(cred_info)) - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, NetworkSecurityTransport, Callable[..., NetworkSecurityTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the network security 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 (Optional[Union[str,NetworkSecurityTransport,Callable[..., NetworkSecurityTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the NetworkSecurityTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "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). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS 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. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - 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. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = NetworkSecurityClient._read_environment_variables() - self._client_cert_source = NetworkSecurityClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = NetworkSecurityClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, NetworkSecurityTransport) - if transport_provided: - # transport is a NetworkSecurityTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(NetworkSecurityTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - NetworkSecurityClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[NetworkSecurityTransport], Callable[..., NetworkSecurityTransport]] = ( - NetworkSecurityClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., NetworkSecurityTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.networksecurity_v1beta1.NetworkSecurityClient`.", - extra = { - "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "credentialsType": None, - } - ) - - def list_authorization_policies(self, - request: Optional[Union[authorization_policy.ListAuthorizationPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAuthorizationPoliciesPager: - r"""Lists AuthorizationPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_list_authorization_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListAuthorizationPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_authorization_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest, dict]): - The request object. Request used with the - ListAuthorizationPolicies method. - parent (str): - Required. The project and location from which the - AuthorizationPolicies should be listed, specified in the - format ``projects/{project}/locations/{location}``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.services.network_security.pagers.ListAuthorizationPoliciesPager: - Response returned by the - ListAuthorizationPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.ListAuthorizationPoliciesRequest): - request = authorization_policy.ListAuthorizationPoliciesRequest(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_authorization_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.ListAuthorizationPoliciesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_authorization_policy(self, - request: Optional[Union[authorization_policy.GetAuthorizationPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> authorization_policy.AuthorizationPolicy: - r"""Gets details of a single AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_get_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_authorization_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.GetAuthorizationPolicyRequest, dict]): - The request object. Request used by the - GetAuthorizationPolicy method. - name (str): - Required. A name of the AuthorizationPolicy to get. Must - be in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.types.AuthorizationPolicy: - AuthorizationPolicy is a resource - that specifies how a server should - authorize incoming connections. This - resource in itself does not change the - configuration unless it's attached to a - target https proxy or endpoint config - selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.GetAuthorizationPolicyRequest): - request = authorization_policy.GetAuthorizationPolicyRequest(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_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_authorization_policy(self, - request: Optional[Union[gcn_authorization_policy.CreateAuthorizationPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, - authorization_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new AuthorizationPolicy in a given project - and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_create_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1beta1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1beta1.CreateAuthorizationPolicyRequest( - parent="parent_value", - authorization_policy_id="authorization_policy_id_value", - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.create_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.CreateAuthorizationPolicyRequest, dict]): - The request object. Request used by the - CreateAuthorizationPolicy method. - parent (str): - Required. The parent resource of the - AuthorizationPolicy. Must be in the format - ``projects/{project}/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - authorization_policy (google.cloud.network_security_v1beta1.types.AuthorizationPolicy): - Required. AuthorizationPolicy - resource to be created. - - This corresponds to the ``authorization_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - authorization_policy_id (str): - Required. Short name of the AuthorizationPolicy resource - to be created. This value should be 1-63 characters - long, containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "authz_policy". - - This corresponds to the ``authorization_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server - should authorize incoming connections. This resource - in itself does not change the configuration unless - it's attached to a target https proxy or endpoint - config selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, authorization_policy, authorization_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_authorization_policy.CreateAuthorizationPolicyRequest): - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if authorization_policy is not None: - request.authorization_policy = authorization_policy - if authorization_policy_id is not None: - request.authorization_policy_id = authorization_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_authorization_policy.AuthorizationPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_authorization_policy(self, - request: Optional[Union[gcn_authorization_policy.UpdateAuthorizationPolicyRequest, dict]] = None, - *, - authorization_policy: Optional[gcn_authorization_policy.AuthorizationPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single - AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_update_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1beta1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1beta1.UpdateAuthorizationPolicyRequest( - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.update_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.UpdateAuthorizationPolicyRequest, dict]): - The request object. Request used by the - UpdateAuthorizationPolicy method. - authorization_policy (google.cloud.network_security_v1beta1.types.AuthorizationPolicy): - Required. Updated AuthorizationPolicy - resource. - - This corresponds to the ``authorization_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the AuthorizationPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.AuthorizationPolicy` AuthorizationPolicy is a resource that specifies how a server - should authorize incoming connections. This resource - in itself does not change the configuration unless - it's attached to a target https proxy or endpoint - config selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [authorization_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_authorization_policy.UpdateAuthorizationPolicyRequest): - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if authorization_policy is not None: - request.authorization_policy = authorization_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_authorization_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("authorization_policy.name", request.authorization_policy.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_authorization_policy.AuthorizationPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_authorization_policy(self, - request: Optional[Union[authorization_policy.DeleteAuthorizationPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a single AuthorizationPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_delete_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.DeleteAuthorizationPolicyRequest, dict]): - The request object. Request used by the - DeleteAuthorizationPolicy method. - name (str): - Required. A name of the AuthorizationPolicy to delete. - Must be in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, authorization_policy.DeleteAuthorizationPolicyRequest): - request = authorization_policy.DeleteAuthorizationPolicyRequest(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_authorization_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def list_server_tls_policies(self, - request: Optional[Union[server_tls_policy.ListServerTlsPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListServerTlsPoliciesPager: - r"""Lists ServerTlsPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_list_server_tls_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListServerTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_server_tls_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest, dict]): - The request object. Request used by the - ListServerTlsPolicies method. - parent (str): - Required. The project and location from which the - ServerTlsPolicies should be listed, specified in the - format ``projects/*/locations/{location}``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.services.network_security.pagers.ListServerTlsPoliciesPager: - Response returned by the - ListServerTlsPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.ListServerTlsPoliciesRequest): - request = server_tls_policy.ListServerTlsPoliciesRequest(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_server_tls_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.ListServerTlsPoliciesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_server_tls_policy(self, - request: Optional[Union[server_tls_policy.GetServerTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> server_tls_policy.ServerTlsPolicy: - r"""Gets details of a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_get_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_server_tls_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.GetServerTlsPolicyRequest, dict]): - The request object. Request used by the - GetServerTlsPolicy method. - name (str): - Required. A name of the ServerTlsPolicy to get. Must be - in the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.types.ServerTlsPolicy: - ServerTlsPolicy is a resource that - specifies how a server should - authenticate incoming requests. This - resource itself does not affect - configuration unless it is attached to a - target https proxy or endpoint config - selector resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.GetServerTlsPolicyRequest): - request = server_tls_policy.GetServerTlsPolicyRequest(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_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_server_tls_policy(self, - request: Optional[Union[gcn_server_tls_policy.CreateServerTlsPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, - server_tls_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new ServerTlsPolicy in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_create_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1beta1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1beta1.CreateServerTlsPolicyRequest( - parent="parent_value", - server_tls_policy_id="server_tls_policy_id_value", - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.create_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.CreateServerTlsPolicyRequest, dict]): - The request object. Request used by the - CreateServerTlsPolicy method. - parent (str): - Required. The parent resource of the ServerTlsPolicy. - Must be in the format - ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - server_tls_policy (google.cloud.network_security_v1beta1.types.ServerTlsPolicy): - Required. ServerTlsPolicy resource to - be created. - - This corresponds to the ``server_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - server_tls_policy_id (str): - Required. Short name of the ServerTlsPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "server_mtls_policy". - - This corresponds to the ``server_tls_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate - incoming requests. This resource itself does not - affect configuration unless it is attached to a - target https proxy or endpoint config selector - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, server_tls_policy, server_tls_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_server_tls_policy.CreateServerTlsPolicyRequest): - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if server_tls_policy is not None: - request.server_tls_policy = server_tls_policy - if server_tls_policy_id is not None: - request.server_tls_policy_id = server_tls_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_server_tls_policy.ServerTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_server_tls_policy(self, - request: Optional[Union[gcn_server_tls_policy.UpdateServerTlsPolicyRequest, dict]] = None, - *, - server_tls_policy: Optional[gcn_server_tls_policy.ServerTlsPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_update_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1beta1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1beta1.UpdateServerTlsPolicyRequest( - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.update_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.UpdateServerTlsPolicyRequest, dict]): - The request object. Request used by UpdateServerTlsPolicy - method. - server_tls_policy (google.cloud.network_security_v1beta1.types.ServerTlsPolicy): - Required. Updated ServerTlsPolicy - resource. - - This corresponds to the ``server_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the ServerTlsPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.ServerTlsPolicy` ServerTlsPolicy is a resource that specifies how a server should authenticate - incoming requests. This resource itself does not - affect configuration unless it is attached to a - target https proxy or endpoint config selector - resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [server_tls_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_server_tls_policy.UpdateServerTlsPolicyRequest): - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if server_tls_policy is not None: - request.server_tls_policy = server_tls_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_server_tls_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("server_tls_policy.name", request.server_tls_policy.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_server_tls_policy.ServerTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_server_tls_policy(self, - request: Optional[Union[server_tls_policy.DeleteServerTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a single ServerTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_delete_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.DeleteServerTlsPolicyRequest, dict]): - The request object. Request used by the - DeleteServerTlsPolicy method. - name (str): - Required. A name of the ServerTlsPolicy to delete. Must - be in the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, server_tls_policy.DeleteServerTlsPolicyRequest): - request = server_tls_policy.DeleteServerTlsPolicyRequest(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_server_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def list_client_tls_policies(self, - request: Optional[Union[client_tls_policy.ListClientTlsPoliciesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListClientTlsPoliciesPager: - r"""Lists ClientTlsPolicies in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest, dict]): - The request object. Request used by the - ListClientTlsPolicies method. - parent (str): - Required. The project and location from which the - ClientTlsPolicies should be listed, specified in the - format ``projects/*/locations/{location}``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.services.network_security.pagers.ListClientTlsPoliciesPager: - Response returned by the - ListClientTlsPolicies method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.ListClientTlsPoliciesRequest): - request = client_tls_policy.ListClientTlsPoliciesRequest(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_client_tls_policies] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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.ListClientTlsPoliciesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_client_tls_policy(self, - request: Optional[Union[client_tls_policy.GetClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> client_tls_policy.ClientTlsPolicy: - r"""Gets details of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.GetClientTlsPolicyRequest, dict]): - The request object. Request used by the - GetClientTlsPolicy method. - name (str): - Required. A name of the ClientTlsPolicy to get. Must be - in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.network_security_v1beta1.types.ClientTlsPolicy: - ClientTlsPolicy is a resource that - specifies how a client should - authenticate connections to backends of - a service. This resource itself does not - affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.GetClientTlsPolicyRequest): - request = client_tls_policy.GetClientTlsPolicyRequest(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_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.CreateClientTlsPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - client_tls_policy_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new ClientTlsPolicy in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1beta1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1beta1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.CreateClientTlsPolicyRequest, dict]): - The request object. Request used by the - CreateClientTlsPolicy method. - parent (str): - Required. The parent resource of the ClientTlsPolicy. - Must be in the format - ``projects/*/locations/{location}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy (google.cloud.network_security_v1beta1.types.ClientTlsPolicy): - Required. ClientTlsPolicy resource to - be created. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - client_tls_policy_id (str): - Required. Short name of the ClientTlsPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and - underscores, and should not start with a number. E.g. - "client_mtls_policy". - - This corresponds to the ``client_tls_policy_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [parent, client_tls_policy, client_tls_policy_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.CreateClientTlsPolicyRequest): - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if client_tls_policy_id is not None: - request.client_tls_policy_id = client_tls_policy_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_client_tls_policy(self, - request: Optional[Union[gcn_client_tls_policy.UpdateClientTlsPolicyRequest, dict]] = None, - *, - client_tls_policy: Optional[gcn_client_tls_policy.ClientTlsPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1beta1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1beta1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.UpdateClientTlsPolicyRequest, dict]): - The request object. Request used by UpdateClientTlsPolicy - method. - client_tls_policy (google.cloud.network_security_v1beta1.types.ClientTlsPolicy): - Required. Updated ClientTlsPolicy - resource. - - This corresponds to the ``client_tls_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the ClientTlsPolicy resource by the - update. The fields specified in the update_mask are - relative to the resource, not the full request. A field - will be overwritten if it is in the mask. If the user - does not provide a mask then all fields will be - overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.network_security_v1beta1.types.ClientTlsPolicy` ClientTlsPolicy is a resource that specifies how a client should authenticate - connections to backends of a service. This resource - itself does not affect configuration unless it is - attached to a backend service resource. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [client_tls_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if client_tls_policy is not None: - request.client_tls_policy = client_tls_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_client_tls_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("client_tls_policy.name", request.client_tls_policy.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, - gcn_client_tls_policy.ClientTlsPolicy, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_client_tls_policy(self, - request: Optional[Union[client_tls_policy.DeleteClientTlsPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a single ClientTlsPolicy. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import network_security_v1beta1 - - def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.network_security_v1beta1.types.DeleteClientTlsPolicyRequest, dict]): - The request object. Request used by the - DeleteClientTlsPolicy method. - name (str): - Required. A name of the ClientTlsPolicy to delete. Must - be in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - - 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, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, client_tls_policy.DeleteClientTlsPolicyRequest): - request = client_tls_policy.DeleteClientTlsPolicyRequest(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_client_tls_policy] - - # 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), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=common.OperationMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "NetworkSecurityClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_operations] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.cancel_operation] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_location] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_locations] - - # 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),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - except core_exceptions.GoogleAPICallError as e: - self._add_cred_info_for_auth_errors(e) - raise e - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - -__all__ = ( - "NetworkSecurityClient", -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/pagers.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/pagers.py deleted file mode 100644 index 33ade1db16b6..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/pagers.py +++ /dev/null @@ -1,446 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.cloud.network_security_v1beta1.types import authorization_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy -from google.cloud.network_security_v1beta1.types import server_tls_policy - - -class ListAuthorizationPoliciesPager: - """A pager for iterating through ``list_authorization_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``authorization_policies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAuthorizationPolicies`` requests and continue to iterate - through the ``authorization_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse` - 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[..., authorization_policy.ListAuthorizationPoliciesResponse], - request: authorization_policy.ListAuthorizationPoliciesRequest, - response: authorization_policy.ListAuthorizationPoliciesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = authorization_policy.ListAuthorizationPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[authorization_policy.ListAuthorizationPoliciesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[authorization_policy.AuthorizationPolicy]: - for page in self.pages: - yield from page.authorization_policies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAuthorizationPoliciesAsyncPager: - """A pager for iterating through ``list_authorization_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``authorization_policies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAuthorizationPolicies`` requests and continue to iterate - through the ``authorization_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse` - 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[authorization_policy.ListAuthorizationPoliciesResponse]], - request: authorization_policy.ListAuthorizationPoliciesRequest, - response: authorization_policy.ListAuthorizationPoliciesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = authorization_policy.ListAuthorizationPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[authorization_policy.ListAuthorizationPoliciesResponse]: - 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[authorization_policy.AuthorizationPolicy]: - async def async_generator(): - async for page in self.pages: - for response in page.authorization_policies: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServerTlsPoliciesPager: - """A pager for iterating through ``list_server_tls_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``server_tls_policies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServerTlsPolicies`` requests and continue to iterate - through the ``server_tls_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse` - 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[..., server_tls_policy.ListServerTlsPoliciesResponse], - request: server_tls_policy.ListServerTlsPoliciesRequest, - response: server_tls_policy.ListServerTlsPoliciesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = server_tls_policy.ListServerTlsPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[server_tls_policy.ListServerTlsPoliciesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[server_tls_policy.ServerTlsPolicy]: - for page in self.pages: - yield from page.server_tls_policies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServerTlsPoliciesAsyncPager: - """A pager for iterating through ``list_server_tls_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``server_tls_policies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServerTlsPolicies`` requests and continue to iterate - through the ``server_tls_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse` - 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[server_tls_policy.ListServerTlsPoliciesResponse]], - request: server_tls_policy.ListServerTlsPoliciesRequest, - response: server_tls_policy.ListServerTlsPoliciesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = server_tls_policy.ListServerTlsPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[server_tls_policy.ListServerTlsPoliciesResponse]: - 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[server_tls_policy.ServerTlsPolicy]: - async def async_generator(): - async for page in self.pages: - for response in page.server_tls_policies: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListClientTlsPoliciesPager: - """A pager for iterating through ``list_client_tls_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``client_tls_policies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListClientTlsPolicies`` requests and continue to iterate - through the ``client_tls_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse` - 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[..., client_tls_policy.ListClientTlsPoliciesResponse], - request: client_tls_policy.ListClientTlsPoliciesRequest, - response: client_tls_policy.ListClientTlsPoliciesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[client_tls_policy.ListClientTlsPoliciesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[client_tls_policy.ClientTlsPolicy]: - for page in self.pages: - yield from page.client_tls_policies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListClientTlsPoliciesAsyncPager: - """A pager for iterating through ``list_client_tls_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``client_tls_policies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListClientTlsPolicies`` requests and continue to iterate - through the ``client_tls_policies`` field on the - corresponding responses. - - All the usual :class:`google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse` - 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[client_tls_policy.ListClientTlsPoliciesResponse]], - request: client_tls_policy.ListClientTlsPoliciesRequest, - response: client_tls_policy.ListClientTlsPoliciesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest): - The initial request object. - response (google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = client_tls_policy.ListClientTlsPoliciesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[client_tls_policy.ListClientTlsPoliciesResponse]: - 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[client_tls_policy.ClientTlsPolicy]: - async def async_generator(): - async for page in self.pages: - for response in page.client_tls_policies: - 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/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/README.rst b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/README.rst deleted file mode 100644 index e226a3cdbadb..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`NetworkSecurityTransport` is the ABC for all transports. -- public child `NetworkSecurityGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `NetworkSecurityGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseNetworkSecurityRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `NetworkSecurityRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py deleted file mode 100644 index 280f689c5e71..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 NetworkSecurityTransport -from .grpc import NetworkSecurityGrpcTransport -from .grpc_asyncio import NetworkSecurityGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[NetworkSecurityTransport]] -_transport_registry['grpc'] = NetworkSecurityGrpcTransport -_transport_registry['grpc_asyncio'] = NetworkSecurityGrpcAsyncIOTransport - -__all__ = ( - 'NetworkSecurityTransport', - 'NetworkSecurityGrpcTransport', - 'NetworkSecurityGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/base.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/base.py deleted file mode 100644 index 26a01a6cfc72..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/base.py +++ /dev/null @@ -1,497 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.network_security_v1beta1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1beta1.types import authorization_policy -from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1beta1.types import server_tls_policy -from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class NetworkSecurityTransport(abc.ABC): - """Abstract transport class for NetworkSecurity.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'networksecurity.googleapis.com' - - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # 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 and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_authorization_policies: gapic_v1.method.wrap_method( - self.list_authorization_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_authorization_policy: gapic_v1.method.wrap_method( - self.get_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_authorization_policy: gapic_v1.method.wrap_method( - self.create_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_authorization_policy: gapic_v1.method.wrap_method( - self.update_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_authorization_policy: gapic_v1.method.wrap_method( - self.delete_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_server_tls_policies: gapic_v1.method.wrap_method( - self.list_server_tls_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_server_tls_policy: gapic_v1.method.wrap_method( - self.get_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_server_tls_policy: gapic_v1.method.wrap_method( - self.create_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_server_tls_policy: gapic_v1.method.wrap_method( - self.update_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_server_tls_policy: gapic_v1.method.wrap_method( - self.delete_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_client_tls_policies: gapic_v1.method.wrap_method( - self.list_client_tls_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_client_tls_policy: gapic_v1.method.wrap_method( - self.get_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_client_tls_policy: gapic_v1.method.wrap_method( - self.create_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_client_tls_policy: gapic_v1.method.wrap_method( - self.update_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_client_tls_policy: gapic_v1.method.wrap_method( - self.delete_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_authorization_policies(self) -> Callable[ - [authorization_policy.ListAuthorizationPoliciesRequest], - Union[ - authorization_policy.ListAuthorizationPoliciesResponse, - Awaitable[authorization_policy.ListAuthorizationPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def get_authorization_policy(self) -> Callable[ - [authorization_policy.GetAuthorizationPolicyRequest], - Union[ - authorization_policy.AuthorizationPolicy, - Awaitable[authorization_policy.AuthorizationPolicy] - ]]: - raise NotImplementedError() - - @property - def create_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.CreateAuthorizationPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_authorization_policy(self) -> Callable[ - [authorization_policy.DeleteAuthorizationPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_server_tls_policies(self) -> Callable[ - [server_tls_policy.ListServerTlsPoliciesRequest], - Union[ - server_tls_policy.ListServerTlsPoliciesResponse, - Awaitable[server_tls_policy.ListServerTlsPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def get_server_tls_policy(self) -> Callable[ - [server_tls_policy.GetServerTlsPolicyRequest], - Union[ - server_tls_policy.ServerTlsPolicy, - Awaitable[server_tls_policy.ServerTlsPolicy] - ]]: - raise NotImplementedError() - - @property - def create_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.CreateServerTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_server_tls_policy(self) -> Callable[ - [server_tls_policy.DeleteServerTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - Union[ - client_tls_policy.ListClientTlsPoliciesResponse, - Awaitable[client_tls_policy.ListClientTlsPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - Union[ - client_tls_policy.ClientTlsPolicy, - Awaitable[client_tls_policy.ClientTlsPolicy] - ]]: - raise NotImplementedError() - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'NetworkSecurityTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc.py deleted file mode 100644 index 38be51141758..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc.py +++ /dev/null @@ -1,933 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 json -import logging as std_logging -import pickle -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1beta1.types import authorization_policy -from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1beta1.types import server_tls_policy -from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class NetworkSecurityGrpcTransport(NetworkSecurityTransport): - """gRPC backend transport for NetworkSecurity. - - Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - - 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_authorization_policies(self) -> Callable[ - [authorization_policy.ListAuthorizationPoliciesRequest], - authorization_policy.ListAuthorizationPoliciesResponse]: - r"""Return a callable for the list authorization policies method over gRPC. - - Lists AuthorizationPolicies in a given project and - location. - - Returns: - Callable[[~.ListAuthorizationPoliciesRequest], - ~.ListAuthorizationPoliciesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_authorization_policies' not in self._stubs: - self._stubs['list_authorization_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListAuthorizationPolicies', - request_serializer=authorization_policy.ListAuthorizationPoliciesRequest.serialize, - response_deserializer=authorization_policy.ListAuthorizationPoliciesResponse.deserialize, - ) - return self._stubs['list_authorization_policies'] - - @property - def get_authorization_policy(self) -> Callable[ - [authorization_policy.GetAuthorizationPolicyRequest], - authorization_policy.AuthorizationPolicy]: - r"""Return a callable for the get authorization policy method over gRPC. - - Gets details of a single AuthorizationPolicy. - - Returns: - Callable[[~.GetAuthorizationPolicyRequest], - ~.AuthorizationPolicy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_authorization_policy' not in self._stubs: - self._stubs['get_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetAuthorizationPolicy', - request_serializer=authorization_policy.GetAuthorizationPolicyRequest.serialize, - response_deserializer=authorization_policy.AuthorizationPolicy.deserialize, - ) - return self._stubs['get_authorization_policy'] - - @property - def create_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.CreateAuthorizationPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the create authorization policy method over gRPC. - - Creates a new AuthorizationPolicy in a given project - and location. - - Returns: - Callable[[~.CreateAuthorizationPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_authorization_policy' not in self._stubs: - self._stubs['create_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateAuthorizationPolicy', - request_serializer=gcn_authorization_policy.CreateAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_authorization_policy'] - - @property - def update_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the update authorization policy method over gRPC. - - Updates the parameters of a single - AuthorizationPolicy. - - Returns: - Callable[[~.UpdateAuthorizationPolicyRequest], - ~.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 'update_authorization_policy' not in self._stubs: - self._stubs['update_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateAuthorizationPolicy', - request_serializer=gcn_authorization_policy.UpdateAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_authorization_policy'] - - @property - def delete_authorization_policy(self) -> Callable[ - [authorization_policy.DeleteAuthorizationPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete authorization policy method over gRPC. - - Deletes a single AuthorizationPolicy. - - Returns: - Callable[[~.DeleteAuthorizationPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_authorization_policy' not in self._stubs: - self._stubs['delete_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteAuthorizationPolicy', - request_serializer=authorization_policy.DeleteAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_authorization_policy'] - - @property - def list_server_tls_policies(self) -> Callable[ - [server_tls_policy.ListServerTlsPoliciesRequest], - server_tls_policy.ListServerTlsPoliciesResponse]: - r"""Return a callable for the list server tls policies method over gRPC. - - Lists ServerTlsPolicies in a given project and - location. - - Returns: - Callable[[~.ListServerTlsPoliciesRequest], - ~.ListServerTlsPoliciesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_server_tls_policies' not in self._stubs: - self._stubs['list_server_tls_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListServerTlsPolicies', - request_serializer=server_tls_policy.ListServerTlsPoliciesRequest.serialize, - response_deserializer=server_tls_policy.ListServerTlsPoliciesResponse.deserialize, - ) - return self._stubs['list_server_tls_policies'] - - @property - def get_server_tls_policy(self) -> Callable[ - [server_tls_policy.GetServerTlsPolicyRequest], - server_tls_policy.ServerTlsPolicy]: - r"""Return a callable for the get server tls policy method over gRPC. - - Gets details of a single ServerTlsPolicy. - - Returns: - Callable[[~.GetServerTlsPolicyRequest], - ~.ServerTlsPolicy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_server_tls_policy' not in self._stubs: - self._stubs['get_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetServerTlsPolicy', - request_serializer=server_tls_policy.GetServerTlsPolicyRequest.serialize, - response_deserializer=server_tls_policy.ServerTlsPolicy.deserialize, - ) - return self._stubs['get_server_tls_policy'] - - @property - def create_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.CreateServerTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the create server tls policy method over gRPC. - - Creates a new ServerTlsPolicy in a given project and - location. - - Returns: - Callable[[~.CreateServerTlsPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_server_tls_policy' not in self._stubs: - self._stubs['create_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateServerTlsPolicy', - request_serializer=gcn_server_tls_policy.CreateServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_server_tls_policy'] - - @property - def update_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the update server tls policy method over gRPC. - - Updates the parameters of a single ServerTlsPolicy. - - Returns: - Callable[[~.UpdateServerTlsPolicyRequest], - ~.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 'update_server_tls_policy' not in self._stubs: - self._stubs['update_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateServerTlsPolicy', - request_serializer=gcn_server_tls_policy.UpdateServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_server_tls_policy'] - - @property - def delete_server_tls_policy(self) -> Callable[ - [server_tls_policy.DeleteServerTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete server tls policy method over gRPC. - - Deletes a single ServerTlsPolicy. - - Returns: - Callable[[~.DeleteServerTlsPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_server_tls_policy' not in self._stubs: - self._stubs['delete_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteServerTlsPolicy', - request_serializer=server_tls_policy.DeleteServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_server_tls_policy'] - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - client_tls_policy.ListClientTlsPoliciesResponse]: - r"""Return a callable for the list client tls policies method over gRPC. - - Lists ClientTlsPolicies in a given project and - location. - - Returns: - Callable[[~.ListClientTlsPoliciesRequest], - ~.ListClientTlsPoliciesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: - self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListClientTlsPolicies', - request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, - response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, - ) - return self._stubs['list_client_tls_policies'] - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - client_tls_policy.ClientTlsPolicy]: - r"""Return a callable for the get client tls policy method over gRPC. - - Gets details of a single ClientTlsPolicy. - - Returns: - Callable[[~.GetClientTlsPolicyRequest], - ~.ClientTlsPolicy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: - self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetClientTlsPolicy', - request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, - response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, - ) - return self._stubs['get_client_tls_policy'] - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the create client tls policy method over gRPC. - - Creates a new ClientTlsPolicy in a given project and - location. - - Returns: - Callable[[~.CreateClientTlsPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_client_tls_policy' not in self._stubs: - self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_client_tls_policy'] - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the update client tls policy method over gRPC. - - Updates the parameters of a single ClientTlsPolicy. - - Returns: - Callable[[~.UpdateClientTlsPolicyRequest], - ~.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 'update_client_tls_policy' not in self._stubs: - self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_client_tls_policy'] - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete client tls policy method over gRPC. - - Deletes a single ClientTlsPolicy. - - Returns: - Callable[[~.DeleteClientTlsPolicyRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_client_tls_policy' not in self._stubs: - self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteClientTlsPolicy', - request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_client_tls_policy'] - - def close(self): - self._logged_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'NetworkSecurityGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc_asyncio.py deleted file mode 100644 index 8b645d639442..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/services/network_security/transports/grpc_asyncio.py +++ /dev/null @@ -1,1069 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 inspect -import json -import pickle -import logging as std_logging -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1beta1.types import authorization_policy -from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1beta1.types import server_tls_policy -from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import NetworkSecurityTransport, DEFAULT_CLIENT_INFO -from .grpc import NetworkSecurityGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class NetworkSecurityGrpcAsyncIOTransport(NetworkSecurityTransport): - """gRPC AsyncIO backend transport for NetworkSecurity. - - Network Security API provides resources to configure - authentication and authorization policies. Refer to per API - resource documentation for more information. - - 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'networksecurity.googleapis.com'). - 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 a ``channel`` instance 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 a ``channel`` instance 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[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_authorization_policies(self) -> Callable[ - [authorization_policy.ListAuthorizationPoliciesRequest], - Awaitable[authorization_policy.ListAuthorizationPoliciesResponse]]: - r"""Return a callable for the list authorization policies method over gRPC. - - Lists AuthorizationPolicies in a given project and - location. - - Returns: - Callable[[~.ListAuthorizationPoliciesRequest], - Awaitable[~.ListAuthorizationPoliciesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_authorization_policies' not in self._stubs: - self._stubs['list_authorization_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListAuthorizationPolicies', - request_serializer=authorization_policy.ListAuthorizationPoliciesRequest.serialize, - response_deserializer=authorization_policy.ListAuthorizationPoliciesResponse.deserialize, - ) - return self._stubs['list_authorization_policies'] - - @property - def get_authorization_policy(self) -> Callable[ - [authorization_policy.GetAuthorizationPolicyRequest], - Awaitable[authorization_policy.AuthorizationPolicy]]: - r"""Return a callable for the get authorization policy method over gRPC. - - Gets details of a single AuthorizationPolicy. - - Returns: - Callable[[~.GetAuthorizationPolicyRequest], - Awaitable[~.AuthorizationPolicy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_authorization_policy' not in self._stubs: - self._stubs['get_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetAuthorizationPolicy', - request_serializer=authorization_policy.GetAuthorizationPolicyRequest.serialize, - response_deserializer=authorization_policy.AuthorizationPolicy.deserialize, - ) - return self._stubs['get_authorization_policy'] - - @property - def create_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.CreateAuthorizationPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create authorization policy method over gRPC. - - Creates a new AuthorizationPolicy in a given project - and location. - - Returns: - Callable[[~.CreateAuthorizationPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_authorization_policy' not in self._stubs: - self._stubs['create_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateAuthorizationPolicy', - request_serializer=gcn_authorization_policy.CreateAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_authorization_policy'] - - @property - def update_authorization_policy(self) -> Callable[ - [gcn_authorization_policy.UpdateAuthorizationPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update authorization policy method over gRPC. - - Updates the parameters of a single - AuthorizationPolicy. - - Returns: - Callable[[~.UpdateAuthorizationPolicyRequest], - 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 'update_authorization_policy' not in self._stubs: - self._stubs['update_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateAuthorizationPolicy', - request_serializer=gcn_authorization_policy.UpdateAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_authorization_policy'] - - @property - def delete_authorization_policy(self) -> Callable[ - [authorization_policy.DeleteAuthorizationPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete authorization policy method over gRPC. - - Deletes a single AuthorizationPolicy. - - Returns: - Callable[[~.DeleteAuthorizationPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_authorization_policy' not in self._stubs: - self._stubs['delete_authorization_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteAuthorizationPolicy', - request_serializer=authorization_policy.DeleteAuthorizationPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_authorization_policy'] - - @property - def list_server_tls_policies(self) -> Callable[ - [server_tls_policy.ListServerTlsPoliciesRequest], - Awaitable[server_tls_policy.ListServerTlsPoliciesResponse]]: - r"""Return a callable for the list server tls policies method over gRPC. - - Lists ServerTlsPolicies in a given project and - location. - - Returns: - Callable[[~.ListServerTlsPoliciesRequest], - Awaitable[~.ListServerTlsPoliciesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_server_tls_policies' not in self._stubs: - self._stubs['list_server_tls_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListServerTlsPolicies', - request_serializer=server_tls_policy.ListServerTlsPoliciesRequest.serialize, - response_deserializer=server_tls_policy.ListServerTlsPoliciesResponse.deserialize, - ) - return self._stubs['list_server_tls_policies'] - - @property - def get_server_tls_policy(self) -> Callable[ - [server_tls_policy.GetServerTlsPolicyRequest], - Awaitable[server_tls_policy.ServerTlsPolicy]]: - r"""Return a callable for the get server tls policy method over gRPC. - - Gets details of a single ServerTlsPolicy. - - Returns: - Callable[[~.GetServerTlsPolicyRequest], - Awaitable[~.ServerTlsPolicy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_server_tls_policy' not in self._stubs: - self._stubs['get_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetServerTlsPolicy', - request_serializer=server_tls_policy.GetServerTlsPolicyRequest.serialize, - response_deserializer=server_tls_policy.ServerTlsPolicy.deserialize, - ) - return self._stubs['get_server_tls_policy'] - - @property - def create_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.CreateServerTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create server tls policy method over gRPC. - - Creates a new ServerTlsPolicy in a given project and - location. - - Returns: - Callable[[~.CreateServerTlsPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_server_tls_policy' not in self._stubs: - self._stubs['create_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateServerTlsPolicy', - request_serializer=gcn_server_tls_policy.CreateServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_server_tls_policy'] - - @property - def update_server_tls_policy(self) -> Callable[ - [gcn_server_tls_policy.UpdateServerTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update server tls policy method over gRPC. - - Updates the parameters of a single ServerTlsPolicy. - - Returns: - Callable[[~.UpdateServerTlsPolicyRequest], - 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 'update_server_tls_policy' not in self._stubs: - self._stubs['update_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateServerTlsPolicy', - request_serializer=gcn_server_tls_policy.UpdateServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_server_tls_policy'] - - @property - def delete_server_tls_policy(self) -> Callable[ - [server_tls_policy.DeleteServerTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete server tls policy method over gRPC. - - Deletes a single ServerTlsPolicy. - - Returns: - Callable[[~.DeleteServerTlsPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_server_tls_policy' not in self._stubs: - self._stubs['delete_server_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteServerTlsPolicy', - request_serializer=server_tls_policy.DeleteServerTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_server_tls_policy'] - - @property - def list_client_tls_policies(self) -> Callable[ - [client_tls_policy.ListClientTlsPoliciesRequest], - Awaitable[client_tls_policy.ListClientTlsPoliciesResponse]]: - r"""Return a callable for the list client tls policies method over gRPC. - - Lists ClientTlsPolicies in a given project and - location. - - Returns: - Callable[[~.ListClientTlsPoliciesRequest], - Awaitable[~.ListClientTlsPoliciesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policies' not in self._stubs: - self._stubs['list_client_tls_policies'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/ListClientTlsPolicies', - request_serializer=client_tls_policy.ListClientTlsPoliciesRequest.serialize, - response_deserializer=client_tls_policy.ListClientTlsPoliciesResponse.deserialize, - ) - return self._stubs['list_client_tls_policies'] - - @property - def get_client_tls_policy(self) -> Callable[ - [client_tls_policy.GetClientTlsPolicyRequest], - Awaitable[client_tls_policy.ClientTlsPolicy]]: - r"""Return a callable for the get client tls policy method over gRPC. - - Gets details of a single ClientTlsPolicy. - - Returns: - Callable[[~.GetClientTlsPolicyRequest], - Awaitable[~.ClientTlsPolicy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_client_tls_policy' not in self._stubs: - self._stubs['get_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/GetClientTlsPolicy', - request_serializer=client_tls_policy.GetClientTlsPolicyRequest.serialize, - response_deserializer=client_tls_policy.ClientTlsPolicy.deserialize, - ) - return self._stubs['get_client_tls_policy'] - - @property - def create_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.CreateClientTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create client tls policy method over gRPC. - - Creates a new ClientTlsPolicy in a given project and - location. - - Returns: - Callable[[~.CreateClientTlsPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_client_tls_policy' not in self._stubs: - self._stubs['create_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/CreateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.CreateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_client_tls_policy'] - - @property - def update_client_tls_policy(self) -> Callable[ - [gcn_client_tls_policy.UpdateClientTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update client tls policy method over gRPC. - - Updates the parameters of a single ClientTlsPolicy. - - Returns: - Callable[[~.UpdateClientTlsPolicyRequest], - 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 'update_client_tls_policy' not in self._stubs: - self._stubs['update_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/UpdateClientTlsPolicy', - request_serializer=gcn_client_tls_policy.UpdateClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_client_tls_policy'] - - @property - def delete_client_tls_policy(self) -> Callable[ - [client_tls_policy.DeleteClientTlsPolicyRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete client tls policy method over gRPC. - - Deletes a single ClientTlsPolicy. - - Returns: - Callable[[~.DeleteClientTlsPolicyRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_client_tls_policy' not in self._stubs: - self._stubs['delete_client_tls_policy'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1beta1.NetworkSecurity/DeleteClientTlsPolicy', - request_serializer=client_tls_policy.DeleteClientTlsPolicyRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_client_tls_policy'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_authorization_policies: self._wrap_method( - self.list_authorization_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_authorization_policy: self._wrap_method( - self.get_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_authorization_policy: self._wrap_method( - self.create_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_authorization_policy: self._wrap_method( - self.update_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_authorization_policy: self._wrap_method( - self.delete_authorization_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_server_tls_policies: self._wrap_method( - self.list_server_tls_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_server_tls_policy: self._wrap_method( - self.get_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_server_tls_policy: self._wrap_method( - self.create_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_server_tls_policy: self._wrap_method( - self.update_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_server_tls_policy: self._wrap_method( - self.delete_server_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_client_tls_policies: self._wrap_method( - self.list_client_tls_policies, - default_timeout=None, - client_info=client_info, - ), - self.get_client_tls_policy: self._wrap_method( - self.get_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.create_client_tls_policy: self._wrap_method( - self.create_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_client_tls_policy: self._wrap_method( - self.update_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_client_tls_policy: self._wrap_method( - self.delete_client_tls_policy, - default_timeout=None, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self._logged_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'NetworkSecurityGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/__init__.py deleted file mode 100644 index bda341b438ae..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/__init__.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .authorization_policy import ( - AuthorizationPolicy, - CreateAuthorizationPolicyRequest, - DeleteAuthorizationPolicyRequest, - GetAuthorizationPolicyRequest, - ListAuthorizationPoliciesRequest, - ListAuthorizationPoliciesResponse, - UpdateAuthorizationPolicyRequest, -) -from .client_tls_policy import ( - ClientTlsPolicy, - CreateClientTlsPolicyRequest, - DeleteClientTlsPolicyRequest, - GetClientTlsPolicyRequest, - ListClientTlsPoliciesRequest, - ListClientTlsPoliciesResponse, - UpdateClientTlsPolicyRequest, -) -from .common import ( - OperationMetadata, -) -from .server_tls_policy import ( - CreateServerTlsPolicyRequest, - DeleteServerTlsPolicyRequest, - GetServerTlsPolicyRequest, - ListServerTlsPoliciesRequest, - ListServerTlsPoliciesResponse, - ServerTlsPolicy, - UpdateServerTlsPolicyRequest, -) -from .tls import ( - CertificateProvider, - CertificateProviderInstance, - GrpcEndpoint, - ValidationCA, -) - -__all__ = ( - 'AuthorizationPolicy', - 'CreateAuthorizationPolicyRequest', - 'DeleteAuthorizationPolicyRequest', - 'GetAuthorizationPolicyRequest', - 'ListAuthorizationPoliciesRequest', - 'ListAuthorizationPoliciesResponse', - 'UpdateAuthorizationPolicyRequest', - 'ClientTlsPolicy', - 'CreateClientTlsPolicyRequest', - 'DeleteClientTlsPolicyRequest', - 'GetClientTlsPolicyRequest', - 'ListClientTlsPoliciesRequest', - 'ListClientTlsPoliciesResponse', - 'UpdateClientTlsPolicyRequest', - 'OperationMetadata', - 'CreateServerTlsPolicyRequest', - 'DeleteServerTlsPolicyRequest', - 'GetServerTlsPolicyRequest', - 'ListServerTlsPoliciesRequest', - 'ListServerTlsPoliciesResponse', - 'ServerTlsPolicy', - 'UpdateServerTlsPolicyRequest', - 'CertificateProvider', - 'CertificateProviderInstance', - 'GrpcEndpoint', - 'ValidationCA', -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/authorization_policy.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/authorization_policy.py deleted file mode 100644 index f9548bef9e17..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/authorization_policy.py +++ /dev/null @@ -1,425 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1beta1', - manifest={ - 'AuthorizationPolicy', - 'ListAuthorizationPoliciesRequest', - 'ListAuthorizationPoliciesResponse', - 'GetAuthorizationPolicyRequest', - 'CreateAuthorizationPolicyRequest', - 'UpdateAuthorizationPolicyRequest', - 'DeleteAuthorizationPolicyRequest', - }, -) - - -class AuthorizationPolicy(proto.Message): - r"""AuthorizationPolicy is a resource that specifies how a server - should authorize incoming connections. This resource in itself - does not change the configuration unless it's attached to a - target https proxy or endpoint config selector resource. - - Attributes: - name (str): - Required. Name of the AuthorizationPolicy resource. It - matches pattern - ``projects/{project}/locations/{location}/authorizationPolicies/``. - description (str): - Optional. Free-text description of the - resource. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was updated. - labels (MutableMapping[str, str]): - Optional. Set of label tags associated with - the AuthorizationPolicy resource. - action (google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Action): - Required. The action to take when a rule - match is found. Possible values are "ALLOW" or - "DENY". - rules (MutableSequence[google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Rule]): - Optional. List of rules to match. Note that at least one of - the rules must match in order for the action specified in - the 'action' field to be taken. A rule is a match if there - is a matching source and destination. If left blank, the - action specified in the ``action`` field will be applied on - every request. - """ - class Action(proto.Enum): - r"""Possible values that define what action to take. - - Values: - ACTION_UNSPECIFIED (0): - Default value. - ALLOW (1): - Grant access. - DENY (2): - Deny access. - Deny rules should be avoided unless they are - used to provide a default "deny all" fallback. - """ - ACTION_UNSPECIFIED = 0 - ALLOW = 1 - DENY = 2 - - class Rule(proto.Message): - r"""Specification of rules. - - Attributes: - sources (MutableSequence[google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Rule.Source]): - Optional. List of attributes for the traffic source. All of - the sources must match. A source is a match if both - principals and ip_blocks match. If not set, the action - specified in the 'action' field will be applied without any - rule checks for the source. - destinations (MutableSequence[google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Rule.Destination]): - Optional. List of attributes for the traffic - destination. All of the destinations must match. - A destination is a match if a request matches - all the specified hosts, ports, methods and - headers. If not set, the action specified in the - 'action' field will be applied without any rule - checks for the destination. - """ - - class Source(proto.Message): - r"""Specification of traffic source attributes. - - Attributes: - principals (MutableSequence[str]): - Optional. List of peer identities to match for - authorization. At least one principal should match. Each - peer can be an exact match, or a prefix match (example, - "namespace/*") or a suffix match (example, - "*/service-account") or a presence match "*". Authorization - based on the principal name without certificate validation - (configured by ServerTlsPolicy resource) is considered - insecure. - ip_blocks (MutableSequence[str]): - Optional. List of CIDR ranges to match based - on source IP address. At least one IP block - should match. Single IP (e.g., "1.2.3.4") and - CIDR (e.g., "1.2.3.0/24") are supported. - Authorization based on source IP alone should be - avoided. The IP addresses of any load balancers - or proxies should be considered untrusted. - """ - - principals: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - ip_blocks: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class Destination(proto.Message): - r"""Specification of traffic destination attributes. - - Attributes: - hosts (MutableSequence[str]): - Required. List of host names to match. Matched against the - ":authority" header in http requests. At least one host - should match. Each host can be an exact match, or a prefix - match (example "mydomain.*") or a suffix match (example - "*.myorg.com") or a presence (any) match "*". - ports (MutableSequence[int]): - Required. List of destination ports to match. - At least one port should match. - methods (MutableSequence[str]): - Optional. A list of HTTP methods to match. At - least one method should match. Should not be set - for gRPC services. - http_header_match (google.cloud.network_security_v1beta1.types.AuthorizationPolicy.Rule.Destination.HttpHeaderMatch): - Optional. Match against key:value pair in - http header. Provides a flexible match based on - HTTP headers, for potentially advanced use - cases. At least one header should match. Avoid - using header matches to make authorization - decisions unless there is a strong guarantee - that requests arrive through a trusted client or - proxy. - """ - - class HttpHeaderMatch(proto.Message): - r"""Specification of HTTP header match attributes. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - regex_match (str): - Required. The value of the header must match - the regular expression specified in regexMatch. - For regular expression grammar, please see: - en.cppreference.com/w/cpp/regex/ecmascript For - matching against a port specified in the HTTP - request, use a headerMatch with headerName set - to Host and a regular expression that satisfies - the RFC2616 Host header's port specifier. - - This field is a member of `oneof`_ ``type``. - header_name (str): - Required. The name of the HTTP header to - match. For matching against the HTTP request's - authority, use a headerMatch with the header - name ":authority". For matching a request's - method, use the headerName ":method". - """ - - regex_match: str = proto.Field( - proto.STRING, - number=2, - oneof='type', - ) - header_name: str = proto.Field( - proto.STRING, - number=1, - ) - - hosts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - ports: MutableSequence[int] = proto.RepeatedField( - proto.UINT32, - number=2, - ) - methods: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - http_header_match: 'AuthorizationPolicy.Rule.Destination.HttpHeaderMatch' = proto.Field( - proto.MESSAGE, - number=5, - message='AuthorizationPolicy.Rule.Destination.HttpHeaderMatch', - ) - - sources: MutableSequence['AuthorizationPolicy.Rule.Source'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AuthorizationPolicy.Rule.Source', - ) - destinations: MutableSequence['AuthorizationPolicy.Rule.Destination'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AuthorizationPolicy.Rule.Destination', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - action: Action = proto.Field( - proto.ENUM, - number=6, - enum=Action, - ) - rules: MutableSequence[Rule] = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=Rule, - ) - - -class ListAuthorizationPoliciesRequest(proto.Message): - r"""Request used with the ListAuthorizationPolicies method. - - Attributes: - parent (str): - Required. The project and location from which the - AuthorizationPolicies should be listed, specified in the - format ``projects/{project}/locations/{location}``. - page_size (int): - Maximum number of AuthorizationPolicies to - return per call. - page_token (str): - The value returned by the last - ``ListAuthorizationPoliciesResponse`` Indicates that this is - a continuation of a prior ``ListAuthorizationPolicies`` - call, and that the system should return the next page of - data. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAuthorizationPoliciesResponse(proto.Message): - r"""Response returned by the ListAuthorizationPolicies method. - - Attributes: - authorization_policies (MutableSequence[google.cloud.network_security_v1beta1.types.AuthorizationPolicy]): - List of AuthorizationPolicies resources. - next_page_token (str): - If there might be 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 - - authorization_policies: MutableSequence['AuthorizationPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AuthorizationPolicy', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetAuthorizationPolicyRequest(proto.Message): - r"""Request used by the GetAuthorizationPolicy method. - - Attributes: - name (str): - Required. A name of the AuthorizationPolicy to get. Must be - in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateAuthorizationPolicyRequest(proto.Message): - r"""Request used by the CreateAuthorizationPolicy method. - - Attributes: - parent (str): - Required. The parent resource of the AuthorizationPolicy. - Must be in the format - ``projects/{project}/locations/{location}``. - authorization_policy_id (str): - Required. Short name of the AuthorizationPolicy resource to - be created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and underscores, - and should not start with a number. E.g. "authz_policy". - authorization_policy (google.cloud.network_security_v1beta1.types.AuthorizationPolicy): - Required. AuthorizationPolicy resource to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - authorization_policy_id: str = proto.Field( - proto.STRING, - number=2, - ) - authorization_policy: 'AuthorizationPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='AuthorizationPolicy', - ) - - -class UpdateAuthorizationPolicyRequest(proto.Message): - r"""Request used by the UpdateAuthorizationPolicy method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the AuthorizationPolicy resource by the - update. The fields specified in the update_mask are relative - to the resource, not the full request. A field will be - overwritten if it is in the mask. If the user does not - provide a mask then all fields will be overwritten. - authorization_policy (google.cloud.network_security_v1beta1.types.AuthorizationPolicy): - Required. Updated AuthorizationPolicy - resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - authorization_policy: 'AuthorizationPolicy' = proto.Field( - proto.MESSAGE, - number=2, - message='AuthorizationPolicy', - ) - - -class DeleteAuthorizationPolicyRequest(proto.Message): - r"""Request used by the DeleteAuthorizationPolicy method. - - Attributes: - name (str): - Required. A name of the AuthorizationPolicy to delete. Must - be in the format - ``projects/{project}/locations/{location}/authorizationPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/client_tls_policy.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/client_tls_policy.py deleted file mode 100644 index f3b6cf5050bb..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/client_tls_policy.py +++ /dev/null @@ -1,271 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.network_security_v1beta1.types import tls -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1beta1', - manifest={ - 'ClientTlsPolicy', - 'ListClientTlsPoliciesRequest', - 'ListClientTlsPoliciesResponse', - 'GetClientTlsPolicyRequest', - 'CreateClientTlsPolicyRequest', - 'UpdateClientTlsPolicyRequest', - 'DeleteClientTlsPolicyRequest', - }, -) - - -class ClientTlsPolicy(proto.Message): - r"""ClientTlsPolicy is a resource that specifies how a client - should authenticate connections to backends of a service. This - resource itself does not affect configuration unless it is - attached to a backend service resource. - - Attributes: - name (str): - Required. Name of the ClientTlsPolicy resource. It matches - the pattern - ``projects/*/locations/{location}/clientTlsPolicies/{client_tls_policy}`` - description (str): - Optional. Free-text description of the - resource. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was updated. - labels (MutableMapping[str, str]): - Optional. Set of label tags associated with - the resource. - sni (str): - Optional. Server Name Indication string to - present to the server during TLS handshake. E.g: - "secure.example.com". - client_certificate (google.cloud.network_security_v1beta1.types.CertificateProvider): - Optional. Defines a mechanism to provision - client identity (public and private keys) for - peer to peer authentication. The presence of - this dictates mTLS. - server_validation_ca (MutableSequence[google.cloud.network_security_v1beta1.types.ValidationCA]): - Optional. Defines the mechanism to obtain the - Certificate Authority certificate to validate - the server certificate. If empty, client does - not validate the server certificate. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - sni: str = proto.Field( - proto.STRING, - number=6, - ) - client_certificate: tls.CertificateProvider = proto.Field( - proto.MESSAGE, - number=7, - message=tls.CertificateProvider, - ) - server_validation_ca: MutableSequence[tls.ValidationCA] = proto.RepeatedField( - proto.MESSAGE, - number=8, - message=tls.ValidationCA, - ) - - -class ListClientTlsPoliciesRequest(proto.Message): - r"""Request used by the ListClientTlsPolicies method. - - Attributes: - parent (str): - Required. The project and location from which the - ClientTlsPolicies should be listed, specified in the format - ``projects/*/locations/{location}``. - page_size (int): - Maximum number of ClientTlsPolicies to return - per call. - page_token (str): - The value returned by the last - ``ListClientTlsPoliciesResponse`` Indicates that this is a - continuation of a prior ``ListClientTlsPolicies`` call, and - that the system should return the next page of data. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListClientTlsPoliciesResponse(proto.Message): - r"""Response returned by the ListClientTlsPolicies method. - - Attributes: - client_tls_policies (MutableSequence[google.cloud.network_security_v1beta1.types.ClientTlsPolicy]): - List of ClientTlsPolicy resources. - next_page_token (str): - If there might be 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 - - client_tls_policies: MutableSequence['ClientTlsPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ClientTlsPolicy', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetClientTlsPolicyRequest(proto.Message): - r"""Request used by the GetClientTlsPolicy method. - - Attributes: - name (str): - Required. A name of the ClientTlsPolicy to get. Must be in - the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateClientTlsPolicyRequest(proto.Message): - r"""Request used by the CreateClientTlsPolicy method. - - Attributes: - parent (str): - Required. The parent resource of the ClientTlsPolicy. Must - be in the format ``projects/*/locations/{location}``. - client_tls_policy_id (str): - Required. Short name of the ClientTlsPolicy resource to be - created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and underscores, - and should not start with a number. E.g. - "client_mtls_policy". - client_tls_policy (google.cloud.network_security_v1beta1.types.ClientTlsPolicy): - Required. ClientTlsPolicy resource to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - client_tls_policy_id: str = proto.Field( - proto.STRING, - number=2, - ) - client_tls_policy: 'ClientTlsPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='ClientTlsPolicy', - ) - - -class UpdateClientTlsPolicyRequest(proto.Message): - r"""Request used by UpdateClientTlsPolicy method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the ClientTlsPolicy resource by the update. - The fields specified in the update_mask are relative to the - resource, not the full request. A field will be overwritten - if it is in the mask. If the user does not provide a mask - then all fields will be overwritten. - client_tls_policy (google.cloud.network_security_v1beta1.types.ClientTlsPolicy): - Required. Updated ClientTlsPolicy resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - client_tls_policy: 'ClientTlsPolicy' = proto.Field( - proto.MESSAGE, - number=2, - message='ClientTlsPolicy', - ) - - -class DeleteClientTlsPolicyRequest(proto.Message): - r"""Request used by the DeleteClientTlsPolicy method. - - Attributes: - name (str): - Required. A name of the ClientTlsPolicy to delete. Must be - in the format - ``projects/*/locations/{location}/clientTlsPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/common.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/common.py deleted file mode 100644 index 2a5468412eb1..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/common.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1beta1', - manifest={ - 'OperationMetadata', - }, -) - - -class OperationMetadata(proto.Message): - r"""Represents the metadata of the long-running operation. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation was - created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation finished - running. - target (str): - Output only. Server-defined resource path for - the target of the operation. - verb (str): - Output only. Name of the verb executed by the - operation. - status_message (str): - Output only. Human-readable status of the - operation, if any. - requested_cancellation (bool): - Output only. Identifies whether the user has requested - cancellation of the operation. Operations that have - successfully been cancelled have [Operation.error][] value - with a [google.rpc.Status.code][google.rpc.Status.code] of - 1, corresponding to ``Code.CANCELLED``. - api_version (str): - Output only. API version used to start the - operation. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/network_security.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/network_security.py deleted file mode 100644 index 39f8dac22cf5..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/network_security.py +++ /dev/null @@ -1,26 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1beta1', - manifest={ - }, -) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/server_tls_policy.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/server_tls_policy.py deleted file mode 100644 index 398e8f39b3d0..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/server_tls_policy.py +++ /dev/null @@ -1,296 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.network_security_v1beta1.types import tls -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1beta1', - manifest={ - 'ServerTlsPolicy', - 'ListServerTlsPoliciesRequest', - 'ListServerTlsPoliciesResponse', - 'GetServerTlsPolicyRequest', - 'CreateServerTlsPolicyRequest', - 'UpdateServerTlsPolicyRequest', - 'DeleteServerTlsPolicyRequest', - }, -) - - -class ServerTlsPolicy(proto.Message): - r"""ServerTlsPolicy is a resource that specifies how a server - should authenticate incoming requests. This resource itself does - not affect configuration unless it is attached to a target https - proxy or endpoint config selector resource. - - Attributes: - name (str): - Required. Name of the ServerTlsPolicy resource. It matches - the pattern - ``projects/*/locations/{location}/serverTlsPolicies/{server_tls_policy}`` - description (str): - Free-text description of the resource. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The timestamp when the resource - was updated. - labels (MutableMapping[str, str]): - Set of label tags associated with the - resource. - allow_open (bool): - Determines if server allows plaintext connections. If set to - true, server allows plain text connections. By default, it - is set to false. This setting is not exclusive of other - encryption modes. For example, if ``allow_open`` and - ``mtls_policy`` are set, server allows both plain text and - mTLS connections. See documentation of other encryption - modes to confirm compatibility. - - Consider using it if you wish to upgrade in place your - deployment to TLS while having mixed TLS and non-TLS traffic - reaching port :80. - server_certificate (google.cloud.network_security_v1beta1.types.CertificateProvider): - Defines a mechanism to provision server identity (public and - private keys). Cannot be combined with ``allow_open`` as a - permissive mode that allows both plain text and TLS is not - supported. - mtls_policy (google.cloud.network_security_v1beta1.types.ServerTlsPolicy.MTLSPolicy): - Defines a mechanism to provision peer validation - certificates for peer to peer authentication (Mutual TLS - - mTLS). If not specified, client certificate will not be - requested. The connection is treated as TLS and not mTLS. If - ``allow_open`` and ``mtls_policy`` are set, server allows - both plain text and mTLS connections. - """ - - class MTLSPolicy(proto.Message): - r"""Specification of the MTLSPolicy. - - Attributes: - client_validation_ca (MutableSequence[google.cloud.network_security_v1beta1.types.ValidationCA]): - Defines the mechanism to obtain the - Certificate Authority certificate to validate - the client certificate. - """ - - client_validation_ca: MutableSequence[tls.ValidationCA] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=tls.ValidationCA, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=5, - ) - allow_open: bool = proto.Field( - proto.BOOL, - number=6, - ) - server_certificate: tls.CertificateProvider = proto.Field( - proto.MESSAGE, - number=7, - message=tls.CertificateProvider, - ) - mtls_policy: MTLSPolicy = proto.Field( - proto.MESSAGE, - number=8, - message=MTLSPolicy, - ) - - -class ListServerTlsPoliciesRequest(proto.Message): - r"""Request used by the ListServerTlsPolicies method. - - Attributes: - parent (str): - Required. The project and location from which the - ServerTlsPolicies should be listed, specified in the format - ``projects/*/locations/{location}``. - page_size (int): - Maximum number of ServerTlsPolicies to return - per call. - page_token (str): - The value returned by the last - ``ListServerTlsPoliciesResponse`` Indicates that this is a - continuation of a prior ``ListServerTlsPolicies`` call, and - that the system should return the next page of data. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListServerTlsPoliciesResponse(proto.Message): - r"""Response returned by the ListServerTlsPolicies method. - - Attributes: - server_tls_policies (MutableSequence[google.cloud.network_security_v1beta1.types.ServerTlsPolicy]): - List of ServerTlsPolicy resources. - next_page_token (str): - If there might be 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 - - server_tls_policies: MutableSequence['ServerTlsPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ServerTlsPolicy', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetServerTlsPolicyRequest(proto.Message): - r"""Request used by the GetServerTlsPolicy method. - - Attributes: - name (str): - Required. A name of the ServerTlsPolicy to get. Must be in - the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateServerTlsPolicyRequest(proto.Message): - r"""Request used by the CreateServerTlsPolicy method. - - Attributes: - parent (str): - Required. The parent resource of the ServerTlsPolicy. Must - be in the format ``projects/*/locations/{location}``. - server_tls_policy_id (str): - Required. Short name of the ServerTlsPolicy resource to be - created. This value should be 1-63 characters long, - containing only letters, numbers, hyphens, and underscores, - and should not start with a number. E.g. - "server_mtls_policy". - server_tls_policy (google.cloud.network_security_v1beta1.types.ServerTlsPolicy): - Required. ServerTlsPolicy resource to be - created. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - server_tls_policy_id: str = proto.Field( - proto.STRING, - number=2, - ) - server_tls_policy: 'ServerTlsPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='ServerTlsPolicy', - ) - - -class UpdateServerTlsPolicyRequest(proto.Message): - r"""Request used by UpdateServerTlsPolicy method. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask is used to specify the fields to be - overwritten in the ServerTlsPolicy resource by the update. - The fields specified in the update_mask are relative to the - resource, not the full request. A field will be overwritten - if it is in the mask. If the user does not provide a mask - then all fields will be overwritten. - server_tls_policy (google.cloud.network_security_v1beta1.types.ServerTlsPolicy): - Required. Updated ServerTlsPolicy resource. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - server_tls_policy: 'ServerTlsPolicy' = proto.Field( - proto.MESSAGE, - number=2, - message='ServerTlsPolicy', - ) - - -class DeleteServerTlsPolicyRequest(proto.Message): - r"""Request used by the DeleteServerTlsPolicy method. - - Attributes: - name (str): - Required. A name of the ServerTlsPolicy to delete. Must be - in the format - ``projects/*/locations/{location}/serverTlsPolicies/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/tls.py b/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/tls.py deleted file mode 100644 index df68307eb1c5..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/google/cloud/network_security_v1beta1/types/tls.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.networksecurity.v1beta1', - manifest={ - 'GrpcEndpoint', - 'ValidationCA', - 'CertificateProviderInstance', - 'CertificateProvider', - }, -) - - -class GrpcEndpoint(proto.Message): - r"""Specification of the GRPC Endpoint. - - Attributes: - target_uri (str): - Required. The target URI of the gRPC - endpoint. Only UDS path is supported, and should - start with "unix:". - """ - - target_uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ValidationCA(proto.Message): - r"""Specification of ValidationCA. Defines the mechanism to - obtain the Certificate Authority certificate to validate the - peer certificate. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - grpc_endpoint (google.cloud.network_security_v1beta1.types.GrpcEndpoint): - gRPC specific configuration to access the - gRPC server to obtain the CA certificate. - - This field is a member of `oneof`_ ``type``. - certificate_provider_instance (google.cloud.network_security_v1beta1.types.CertificateProviderInstance): - The certificate provider instance - specification that will be passed to the data - plane, which will be used to load necessary - credential information. - - This field is a member of `oneof`_ ``type``. - """ - - grpc_endpoint: 'GrpcEndpoint' = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message='GrpcEndpoint', - ) - certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( - proto.MESSAGE, - number=3, - oneof='type', - message='CertificateProviderInstance', - ) - - -class CertificateProviderInstance(proto.Message): - r"""Specification of a TLS certificate provider instance. - Workloads may have one or more CertificateProvider instances - (plugins) and one of them is enabled and configured by - specifying this message. Workloads use the values from this - message to locate and load the CertificateProvider instance - configuration. - - Attributes: - plugin_instance (str): - Required. Plugin instance name, used to locate and load - CertificateProvider instance configuration. Set to - "google_cloud_private_spiffe" to use Certificate Authority - Service certificate provider instance. - """ - - plugin_instance: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CertificateProvider(proto.Message): - r"""Specification of certificate provider. Defines the mechanism - to obtain the certificate and private key for peer to peer - authentication. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - grpc_endpoint (google.cloud.network_security_v1beta1.types.GrpcEndpoint): - gRPC specific configuration to access the - gRPC server to obtain the cert and private key. - - This field is a member of `oneof`_ ``type``. - certificate_provider_instance (google.cloud.network_security_v1beta1.types.CertificateProviderInstance): - The certificate provider instance - specification that will be passed to the data - plane, which will be used to load necessary - credential information. - - This field is a member of `oneof`_ ``type``. - """ - - grpc_endpoint: 'GrpcEndpoint' = proto.Field( - proto.MESSAGE, - number=2, - oneof='type', - message='GrpcEndpoint', - ) - certificate_provider_instance: 'CertificateProviderInstance' = proto.Field( - proto.MESSAGE, - number=3, - oneof='type', - message='CertificateProviderInstance', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/mypy.ini b/owl-bot-staging/google-cloud-network-security/v1beta1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/noxfile.py b/owl-bot-staging/google-cloud-network-security/v1beta1/noxfile.py deleted file mode 100644 index 6de174fa4528..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/noxfile.py +++ /dev/null @@ -1,592 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re -import shutil - -from typing import Dict, List -import warnings - -import nox - -BLACK_VERSION = "black[jupyter]==23.7.0" -ISORT_VERSION = "isort==5.11.0" - -LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = "google-cloud-network-security" - -UNIT_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "asyncmock", - "pytest", - "pytest-cov", - "pytest-asyncio", -] -UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] -UNIT_TEST_DEPENDENCIES: List[str] = [] -UNIT_TEST_EXTRAS: List[str] = [] -UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] -SYSTEM_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "pytest", - "google-cloud-testutils", -] -SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_EXTRAS: List[str] = [] -SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -nox.options.sessions = [ - "unit", - "system", - "cover", - "lint", - "lint_setup_py", - "blacken", - "docs", -] - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", - "types-requests", - "types-protobuf", - ) - session.install(".") - session.run( - "mypy", - "-p", - "google", - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "update", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "check", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *LINT_PATHS, - ) - - session.run("flake8", "google", "tests") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def format(session): - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run( - "isort", - "--fss", - *LINT_PATHS, - ) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("setuptools", "docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") - - -def install_unittest_dependencies(session, *constraints): - standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES - session.install(*standard_deps, *constraints) - - if UNIT_TEST_EXTERNAL_DEPENDENCIES: - warnings.warn( - "'unit_test_external_dependencies' is deprecated. Instead, please " - "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", - DeprecationWarning, - ) - session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_LOCAL_DEPENDENCIES: - session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_EXTRAS_BY_PYTHON: - extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif UNIT_TEST_EXTRAS: - extras = UNIT_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def unit(session, protobuf_implementation): - # Install all test dependencies, then install this package in-place. - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - install_unittest_dependencies(session, "-c", constraints_path) - - # TODO(https://github.com/googleapis/synthtool/issues/1976): - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - # Run py.test against the unit tests. - session.run( - "py.test", - "--quiet", - f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=google", - "--cov=tests/unit", - "--cov-append", - "--cov-config=.coveragerc", - "--cov-report=", - "--cov-fail-under=0", - os.path.join("tests", "unit"), - *session.posargs, - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -def install_systemtest_dependencies(session, *constraints): - session.install("--pre", "grpcio") - - session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: - session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_LOCAL_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTRAS_BY_PYTHON: - extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif SYSTEM_TEST_EXTRAS: - extras = SYSTEM_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) -def system(session): - """Run the system test suite.""" - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. - if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": - session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Install pyopenssl for mTLS testing. - if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": - session.install("pyopenssl") - - system_test_exists = os.path.exists(system_test_path) - system_test_folder_exists = os.path.exists(system_test_folder_path) - # Sanity check: only run tests if found. - if not system_test_exists and not system_test_folder_exists: - session.skip("System tests were not found") - - install_systemtest_dependencies(session, "-c", constraints_path) - - # Run py.test against the system tests. - if system_test_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if system_test_folder_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python="3.10") -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "sphinx==4.5.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", ""), - ) - - -@nox.session(python="3.10") -def docfx(session): - """Build the docfx yaml files for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "gcp-sphinx-docfx-yaml", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-D", - ( - "extensions=sphinx.ext.autodoc," - "sphinx.ext.autosummary," - "docfx_yaml.extension," - "sphinx.ext.intersphinx," - "sphinx.ext.coverage," - "sphinx.ext.napoleon," - "sphinx.ext.todo," - "sphinx.ext.viewcode," - "recommonmark" - ), - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def prerelease_deps(session, protobuf_implementation): - """ - Run all tests with pre-release versions of dependencies installed - rather than the standard non pre-release versions. - Pre-release versions can be installed using - `pip install --pre `. - """ - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # Note: If a dependency is added to the `prerel_deps` list, - # the `core_dependencies_from_source` list in the `core_deps_from_source` - # nox session should also be updated. - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpc-google-iam-v1", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--ignore-installed", dep) - # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` - # to the dictionary below once this bug is fixed. - # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add - # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below - # once this bug is fixed. - package_namespaces = { - "google-api-core": "google.api_core", - "google-auth": "google.auth", - "grpcio": "grpc", - "protobuf": "google.protobuf", - "proto-plus": "proto", - } - - version_namespace = package_namespaces.get(dep) - - print(f"Installed {dep}") - if version_namespace: - session.run( - "python", - "-c", - f"import {version_namespace}; print({version_namespace}.__version__)", - ) - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb"], -) -def core_deps_from_source(session, protobuf_implementation): - """Run all tests with core dependencies installed from source - rather than pulling the dependencies from PyPI. - """ - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and - # `grpcio-status` should be added to the list below so that they are installed from source, - # rather than PyPI. - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be - # added to the list below so that it is installed from source, rather than PyPI - # Note: If a dependency is added to the `core_dependencies_from_source` list, - # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. - core_dependencies_from_source = [ - "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", - "google-api-core @ git+https://github.com/googleapis/python-api-core.git", - "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", - "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", - "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", - ] - - for dep in core_dependencies_from_source: - session.install(dep, "--no-deps", "--ignore-installed") - print(f"Installed {dep}") - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py deleted file mode 100644 index 3fbd789329cb..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_create_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1beta1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1beta1.CreateAuthorizationPolicyRequest( - parent="parent_value", - authorization_policy_id="authorization_policy_id_value", - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.create_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py deleted file mode 100644 index be56017460a6..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_create_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1beta1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1beta1.CreateAuthorizationPolicyRequest( - parent="parent_value", - authorization_policy_id="authorization_policy_id_value", - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.create_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py deleted file mode 100644 index 4e1421699aad..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1beta1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1beta1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py deleted file mode 100644 index e66ace52fa5b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_create_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1beta1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1beta1.CreateClientTlsPolicyRequest( - parent="parent_value", - client_tls_policy_id="client_tls_policy_id_value", - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.create_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py deleted file mode 100644 index d58db9e1cd7b..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_create_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1beta1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1beta1.CreateServerTlsPolicyRequest( - parent="parent_value", - server_tls_policy_id="server_tls_policy_id_value", - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.create_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py deleted file mode 100644 index df681431f156..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_create_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1beta1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1beta1.CreateServerTlsPolicyRequest( - parent="parent_value", - server_tls_policy_id="server_tls_policy_id_value", - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.create_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py deleted file mode 100644 index c11cca782530..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_delete_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py deleted file mode 100644 index 0c33c3199057..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_delete_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py deleted file mode 100644 index 6017fdbad8aa..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py deleted file mode 100644 index c0726eb2d399..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_delete_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py deleted file mode 100644 index 7c31990b7d7a..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_delete_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py deleted file mode 100644 index 11e18c3f3760..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_delete_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.DeleteServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py deleted file mode 100644 index 006db5ad1e97..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_get_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_authorization_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py deleted file mode 100644 index 8a6e5d2faaa1..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_get_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetAuthorizationPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_authorization_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py deleted file mode 100644 index 8f0d900d9d38..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py deleted file mode 100644 index 5a0e1a6d9193..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_get_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetClientTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_client_tls_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py deleted file mode 100644 index aa63588350f5..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_get_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_server_tls_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py deleted file mode 100644 index 61a45c8d22ef..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_get_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.GetServerTlsPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_server_tls_policy(request=request) - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py deleted file mode 100644 index 96f5aab5ae6f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAuthorizationPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_list_authorization_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListAuthorizationPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_authorization_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py deleted file mode 100644 index f1896285f252..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAuthorizationPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_list_authorization_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListAuthorizationPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_authorization_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py deleted file mode 100644 index 8755992dec54..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListClientTlsPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py deleted file mode 100644 index 0a925aa6c91a..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListClientTlsPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_list_client_tls_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListClientTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_client_tls_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py deleted file mode 100644 index 3c014a070e38..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServerTlsPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_list_server_tls_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListServerTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_server_tls_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py deleted file mode 100644 index adc15ffe0772..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServerTlsPolicies -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_list_server_tls_policies(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - request = network_security_v1beta1.ListServerTlsPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_server_tls_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py deleted file mode 100644 index d25fc6ca2c68..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_update_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1beta1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1beta1.UpdateAuthorizationPolicyRequest( - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.update_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py deleted file mode 100644 index ad0c06a28f92..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAuthorizationPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_update_authorization_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - authorization_policy = network_security_v1beta1.AuthorizationPolicy() - authorization_policy.name = "name_value" - authorization_policy.action = "DENY" - - request = network_security_v1beta1.UpdateAuthorizationPolicyRequest( - authorization_policy=authorization_policy, - ) - - # Make the request - operation = client.update_authorization_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py deleted file mode 100644 index 17fe7d54e4fb..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1beta1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1beta1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py deleted file mode 100644 index f2cd1e5c4796..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateClientTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_update_client_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - client_tls_policy = network_security_v1beta1.ClientTlsPolicy() - client_tls_policy.name = "name_value" - - request = network_security_v1beta1.UpdateClientTlsPolicyRequest( - client_tls_policy=client_tls_policy, - ) - - # Make the request - operation = client.update_client_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py deleted file mode 100644 index 2700c9392485..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -async def sample_update_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityAsyncClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1beta1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1beta1.UpdateServerTlsPolicyRequest( - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.update_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_async] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py deleted file mode 100644 index 39b8be55daa2..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateServerTlsPolicy -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-network-security - - -# [START networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import network_security_v1beta1 - - -def sample_update_server_tls_policy(): - # Create a client - client = network_security_v1beta1.NetworkSecurityClient() - - # Initialize request argument(s) - server_tls_policy = network_security_v1beta1.ServerTlsPolicy() - server_tls_policy.name = "name_value" - - request = network_security_v1beta1.UpdateServerTlsPolicyRequest( - server_tls_policy=server_tls_policy, - ) - - # Make the request - operation = client.update_server_tls_policy(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync] diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json b/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json deleted file mode 100644 index 71c9b6489c86..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1beta1.json +++ /dev/null @@ -1,2502 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.networksecurity.v1beta1", - "version": "v1beta1" - } - ], - "language": "PYTHON", - "name": "google-cloud-network-security", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.create_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.CreateAuthorizationPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy" - }, - { - "name": "authorization_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_authorization_policy" - }, - "description": "Sample for CreateAuthorizationPolicy", - "file": "networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_create_authorization_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.create_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.CreateAuthorizationPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy" - }, - { - "name": "authorization_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_authorization_policy" - }, - "description": "Sample for CreateAuthorizationPolicy", - "file": "networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_create_authorization_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.create_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.CreateClientTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy" - }, - { - "name": "client_tls_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_client_tls_policy" - }, - "description": "Sample for CreateClientTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_create_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.create_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.CreateClientTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy" - }, - { - "name": "client_tls_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_client_tls_policy" - }, - "description": "Sample for CreateClientTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateClientTlsPolicy_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_create_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.create_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.CreateServerTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy" - }, - { - "name": "server_tls_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_server_tls_policy" - }, - "description": "Sample for CreateServerTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_create_server_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.create_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.CreateServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "CreateServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.CreateServerTlsPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy" - }, - { - "name": "server_tls_policy_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_server_tls_policy" - }, - "description": "Sample for CreateServerTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_CreateServerTlsPolicy_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_create_server_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.delete_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.DeleteAuthorizationPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_authorization_policy" - }, - "description": "Sample for DeleteAuthorizationPolicy", - "file": "networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_delete_authorization_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.delete_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.DeleteAuthorizationPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_authorization_policy" - }, - "description": "Sample for DeleteAuthorizationPolicy", - "file": "networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_delete_authorization_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.delete_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.DeleteClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_client_tls_policy" - }, - "description": "Sample for DeleteClientTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.delete_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.DeleteClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_client_tls_policy" - }, - "description": "Sample for DeleteClientTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_delete_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.delete_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.DeleteServerTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_server_tls_policy" - }, - "description": "Sample for DeleteServerTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.delete_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.DeleteServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "DeleteServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.DeleteServerTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_server_tls_policy" - }, - "description": "Sample for DeleteServerTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_delete_server_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.get_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.GetAuthorizationPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy", - "shortName": "get_authorization_policy" - }, - "description": "Sample for GetAuthorizationPolicy", - "file": "networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_get_authorization_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.get_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.GetAuthorizationPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy", - "shortName": "get_authorization_policy" - }, - "description": "Sample for GetAuthorizationPolicy", - "file": "networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetAuthorizationPolicy_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_get_authorization_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.get_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.GetClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy", - "shortName": "get_client_tls_policy" - }, - "description": "Sample for GetClientTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_get_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.get_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.GetClientTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy", - "shortName": "get_client_tls_policy" - }, - "description": "Sample for GetClientTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetClientTlsPolicy_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_get_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.get_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.GetServerTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy", - "shortName": "get_server_tls_policy" - }, - "description": "Sample for GetServerTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_get_server_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.get_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.GetServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "GetServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.GetServerTlsPolicyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy", - "shortName": "get_server_tls_policy" - }, - "description": "Sample for GetServerTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_GetServerTlsPolicy_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_get_server_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.list_authorization_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListAuthorizationPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListAuthorizationPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager", - "shortName": "list_authorization_policies" - }, - "description": "Sample for ListAuthorizationPolicies", - "file": "networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_list_authorization_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.list_authorization_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListAuthorizationPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListAuthorizationPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.ListAuthorizationPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListAuthorizationPoliciesPager", - "shortName": "list_authorization_policies" - }, - "description": "Sample for ListAuthorizationPolicies", - "file": "networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListAuthorizationPolicies_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_list_authorization_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.list_client_tls_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListClientTlsPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListClientTlsPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager", - "shortName": "list_client_tls_policies" - }, - "description": "Sample for ListClientTlsPolicies", - "file": "networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_list_client_tls_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.list_client_tls_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListClientTlsPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListClientTlsPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.ListClientTlsPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListClientTlsPoliciesPager", - "shortName": "list_client_tls_policies" - }, - "description": "Sample for ListClientTlsPolicies", - "file": "networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListClientTlsPolicies_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_list_client_tls_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.list_server_tls_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListServerTlsPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListServerTlsPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager", - "shortName": "list_server_tls_policies" - }, - "description": "Sample for ListServerTlsPolicies", - "file": "networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_list_server_tls_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.list_server_tls_policies", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.ListServerTlsPolicies", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "ListServerTlsPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.ListServerTlsPoliciesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.network_security_v1beta1.services.network_security.pagers.ListServerTlsPoliciesPager", - "shortName": "list_server_tls_policies" - }, - "description": "Sample for ListServerTlsPolicies", - "file": "networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_ListServerTlsPolicies_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_list_server_tls_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.update_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.UpdateAuthorizationPolicyRequest" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_authorization_policy" - }, - "description": "Sample for UpdateAuthorizationPolicy", - "file": "networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_update_authorization_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.update_authorization_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateAuthorizationPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateAuthorizationPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.UpdateAuthorizationPolicyRequest" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1beta1.types.AuthorizationPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_authorization_policy" - }, - "description": "Sample for UpdateAuthorizationPolicy", - "file": "networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_update_authorization_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.update_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.UpdateClientTlsPolicyRequest" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_client_tls_policy" - }, - "description": "Sample for UpdateClientTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_update_client_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.update_client_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateClientTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateClientTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.UpdateClientTlsPolicyRequest" - }, - { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1beta1.types.ClientTlsPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_client_tls_policy" - }, - "description": "Sample for UpdateClientTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_update_client_tls_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityAsyncClient.update_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.UpdateServerTlsPolicyRequest" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_server_tls_policy" - }, - "description": "Sample for UpdateServerTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_async", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_update_server_tls_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" - }, - "fullName": "google.cloud.network_security_v1beta1.NetworkSecurityClient.update_server_tls_policy", - "method": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity.UpdateServerTlsPolicy", - "service": { - "fullName": "google.cloud.networksecurity.v1beta1.NetworkSecurity", - "shortName": "NetworkSecurity" - }, - "shortName": "UpdateServerTlsPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.network_security_v1beta1.types.UpdateServerTlsPolicyRequest" - }, - { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1beta1.types.ServerTlsPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_server_tls_policy" - }, - "description": "Sample for UpdateServerTlsPolicy", - "file": "networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1beta1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync", - "segments": [ - { - "end": 58, - "start": 27, - "type": "FULL" - }, - { - "end": 58, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 55, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 59, - "start": 56, - "type": "RESPONSE_HANDLING" - } - ], - "title": "networksecurity_v1beta1_generated_network_security_update_server_tls_policy_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/scripts/fixup_network_security_v1beta1_keywords.py b/owl-bot-staging/google-cloud-network-security/v1beta1/scripts/fixup_network_security_v1beta1_keywords.py deleted file mode 100644 index f383005222af..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/scripts/fixup_network_security_v1beta1_keywords.py +++ /dev/null @@ -1,190 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 network_securityCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_authorization_policy': ('parent', 'authorization_policy_id', 'authorization_policy', ), - 'create_client_tls_policy': ('parent', 'client_tls_policy_id', 'client_tls_policy', ), - 'create_server_tls_policy': ('parent', 'server_tls_policy_id', 'server_tls_policy', ), - 'delete_authorization_policy': ('name', ), - 'delete_client_tls_policy': ('name', ), - 'delete_server_tls_policy': ('name', ), - 'get_authorization_policy': ('name', ), - 'get_client_tls_policy': ('name', ), - 'get_server_tls_policy': ('name', ), - 'list_authorization_policies': ('parent', 'page_size', 'page_token', ), - 'list_client_tls_policies': ('parent', 'page_size', 'page_token', ), - 'list_server_tls_policies': ('parent', 'page_size', 'page_token', ), - 'update_authorization_policy': ('authorization_policy', 'update_mask', ), - 'update_client_tls_policy': ('client_tls_policy', 'update_mask', ), - 'update_server_tls_policy': ('server_tls_policy', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=network_securityCallTransformer(), -): - """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 network_security 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/google-cloud-network-security/v1beta1/setup.py b/owl-bot-staging/google-cloud-network-security/v1beta1/setup.py deleted file mode 100644 index 1f618aa7ad2f..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-network-security' - - -description = "Google Cloud Network Security API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/network_security/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0", - "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", - "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.14.0, <1.0.0", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.13.txt deleted file mode 100644 index 2010e549cceb..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.13.txt +++ /dev/null @@ -1,12 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -proto-plus>=1 -protobuf>=6 -grpc-google-iam-v1>=0 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.7.txt deleted file mode 100644 index 56affbd9bd75..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.14.0 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-network-security/v1beta1/tests/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1beta1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/__init__.py b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/test_network_security.py b/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/test_network_security.py deleted file mode 100644 index fe8384a82e77..000000000000 --- a/owl-bot-staging/google-cloud-network-security/v1beta1/tests/unit/gapic/network_security_v1beta1/test_network_security.py +++ /dev/null @@ -1,8936 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2025 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.location import locations_pb2 -from google.cloud.network_security_v1beta1.services.network_security import NetworkSecurityAsyncClient -from google.cloud.network_security_v1beta1.services.network_security import NetworkSecurityClient -from google.cloud.network_security_v1beta1.services.network_security import pagers -from google.cloud.network_security_v1beta1.services.network_security import transports -from google.cloud.network_security_v1beta1.types import authorization_policy -from google.cloud.network_security_v1beta1.types import authorization_policy as gcn_authorization_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy -from google.cloud.network_security_v1beta1.types import client_tls_policy as gcn_client_tls_policy -from google.cloud.network_security_v1beta1.types import common -from google.cloud.network_security_v1beta1.types import server_tls_policy -from google.cloud.network_security_v1beta1.types import server_tls_policy as gcn_server_tls_policy -from google.cloud.network_security_v1beta1.types import tls -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - - -CRED_INFO_JSON = { - "credential_source": "/path/to/file", - "credential_type": "service account credentials", - "principal": "service-account@example.com", -} -CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# 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 - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -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 NetworkSecurityClient._get_default_mtls_endpoint(None) is None - assert NetworkSecurityClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert NetworkSecurityClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert NetworkSecurityClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - NetworkSecurityClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - NetworkSecurityClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert NetworkSecurityClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert NetworkSecurityClient._get_client_cert_source(None, False) is None - assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert NetworkSecurityClient._get_client_cert_source(None, True) is mock_default_cert_source - assert NetworkSecurityClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE - default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert NetworkSecurityClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - assert NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == NetworkSecurityClient.DEFAULT_MTLS_ENDPOINT - assert NetworkSecurityClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert NetworkSecurityClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - NetworkSecurityClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert NetworkSecurityClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert NetworkSecurityClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert NetworkSecurityClient._get_universe_domain(None, None) == NetworkSecurityClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - NetworkSecurityClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) -def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): - cred = mock.Mock(["get_cred_info"]) - cred.get_cred_info = mock.Mock(return_value=cred_info_json) - client = NetworkSecurityClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=["foo"]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - if show_cred_info: - assert error.details == ["foo", CRED_INFO_STRING] - else: - assert error.details == ["foo"] - -@pytest.mark.parametrize("error_code", [401,403,404,500]) -def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): - cred = mock.Mock([]) - assert not hasattr(cred, "get_cred_info") - client = NetworkSecurityClient(credentials=cred) - client._transport._credentials = cred - - error = core_exceptions.GoogleAPICallError("message", details=[]) - error.code = error_code - - client._add_cred_info_for_auth_errors(error) - assert error.details == [] - -@pytest.mark.parametrize("client_class,transport_name", [ - (NetworkSecurityClient, "grpc"), - (NetworkSecurityAsyncClient, "grpc_asyncio"), -]) -def test_network_security_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.NetworkSecurityGrpcTransport, "grpc"), - (transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_network_security_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (NetworkSecurityClient, "grpc"), - (NetworkSecurityAsyncClient, "grpc_asyncio"), -]) -def test_network_security_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - ) - - -def test_network_security_client_get_transport_class(): - transport = NetworkSecurityClient.get_transport_class() - available_transports = [ - transports.NetworkSecurityGrpcTransport, - ] - assert transport in available_transports - - transport = NetworkSecurityClient.get_transport_class("grpc") - assert transport == transports.NetworkSecurityGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -def test_network_security_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(NetworkSecurityClient, '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(NetworkSecurityClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "true"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", "false"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_network_security_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - NetworkSecurityClient, NetworkSecurityAsyncClient -]) -@mock.patch.object(NetworkSecurityClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(NetworkSecurityAsyncClient)) -def test_network_security_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # 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) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - NetworkSecurityClient, NetworkSecurityAsyncClient -]) -@mock.patch.object(NetworkSecurityClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityClient)) -@mock.patch.object(NetworkSecurityAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(NetworkSecurityAsyncClient)) -def test_network_security_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = NetworkSecurityClient._DEFAULT_UNIVERSE - default_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = NetworkSecurityClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc"), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_network_security_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_network_security_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_network_security_client_client_options_from_dict(): - with mock.patch('google.cloud.network_security_v1beta1.services.network_security.transports.NetworkSecurityGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = NetworkSecurityClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport, "grpc", grpc_helpers), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_network_security_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "networksecurity.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="networksecurity.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - authorization_policy.ListAuthorizationPoliciesRequest, - dict, -]) -def test_list_authorization_policies(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_authorization_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = authorization_policy.ListAuthorizationPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizationPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_authorization_policies_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = authorization_policy.ListAuthorizationPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_authorization_policies(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == authorization_policy.ListAuthorizationPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_authorization_policies_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_authorization_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_authorization_policies] = mock_rpc - request = {} - client.list_authorization_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_authorization_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_authorization_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_authorization_policies in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_authorization_policies] = mock_rpc - - request = {} - await client.list_authorization_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_authorization_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_authorization_policies_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.ListAuthorizationPoliciesRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_authorization_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = authorization_policy.ListAuthorizationPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAuthorizationPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_authorization_policies_async_from_dict(): - await test_list_authorization_policies_async(request_type=dict) - -def test_list_authorization_policies_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.ListAuthorizationPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() - client.list_authorization_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_authorization_policies_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.ListAuthorizationPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse()) - await client.list_authorization_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_authorization_policies_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_authorization_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_authorization_policies_flattened_error(): - client = NetworkSecurityClient( - 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_authorization_policies( - authorization_policy.ListAuthorizationPoliciesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_authorization_policies_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_authorization_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_authorization_policies_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_authorization_policies( - authorization_policy.ListAuthorizationPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_authorization_policies_pager(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='abc', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[], - next_page_token='def', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='ghi', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_authorization_policies(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, authorization_policy.AuthorizationPolicy) - for i in results) -def test_list_authorization_policies_pages(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='abc', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[], - next_page_token='def', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='ghi', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_authorization_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_list_authorization_policies_async_pager(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='abc', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[], - next_page_token='def', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='ghi', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_authorization_policies(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, authorization_policy.AuthorizationPolicy) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_authorization_policies_async_pages(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='abc', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[], - next_page_token='def', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - ], - next_page_token='ghi', - ), - authorization_policy.ListAuthorizationPoliciesResponse( - authorization_policies=[ - authorization_policy.AuthorizationPolicy(), - authorization_policy.AuthorizationPolicy(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_authorization_policies(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - authorization_policy.GetAuthorizationPolicyRequest, - dict, -]) -def test_get_authorization_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.AuthorizationPolicy( - name='name_value', - description='description_value', - action=authorization_policy.AuthorizationPolicy.Action.ALLOW, - ) - response = client.get_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = authorization_policy.GetAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, authorization_policy.AuthorizationPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW - - -def test_get_authorization_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = authorization_policy.GetAuthorizationPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_authorization_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == authorization_policy.GetAuthorizationPolicyRequest( - name='name_value', - ) - -def test_get_authorization_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_authorization_policy] = mock_rpc - request = {} - client.get_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_authorization_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_authorization_policy] = mock_rpc - - request = {} - await client.get_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.GetAuthorizationPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy( - name='name_value', - description='description_value', - action=authorization_policy.AuthorizationPolicy.Action.ALLOW, - )) - response = await client.get_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = authorization_policy.GetAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, authorization_policy.AuthorizationPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.action == authorization_policy.AuthorizationPolicy.Action.ALLOW - - -@pytest.mark.asyncio -async def test_get_authorization_policy_async_from_dict(): - await test_get_authorization_policy_async(request_type=dict) - -def test_get_authorization_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.GetAuthorizationPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - call.return_value = authorization_policy.AuthorizationPolicy() - client.get_authorization_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_authorization_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.GetAuthorizationPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy()) - await client.get_authorization_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_authorization_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.AuthorizationPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_authorization_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_authorization_policy_flattened_error(): - client = NetworkSecurityClient( - 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_authorization_policy( - authorization_policy.GetAuthorizationPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_authorization_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = authorization_policy.AuthorizationPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_authorization_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_authorization_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_authorization_policy( - authorization_policy.GetAuthorizationPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_authorization_policy.CreateAuthorizationPolicyRequest, - dict, -]) -def test_create_authorization_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_authorization_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest( - parent='parent_value', - authorization_policy_id='authorization_policy_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_authorization_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_authorization_policy.CreateAuthorizationPolicyRequest( - parent='parent_value', - authorization_policy_id='authorization_policy_id_value', - ) - -def test_create_authorization_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_authorization_policy] = mock_rpc - request = {} - client.create_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_authorization_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_authorization_policy] = mock_rpc - - request = {} - await client.create_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_authorization_policy.CreateAuthorizationPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_authorization_policy_async_from_dict(): - await test_create_authorization_policy_async(request_type=dict) - -def test_create_authorization_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_authorization_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_authorization_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_authorization_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_authorization_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_authorization_policy( - parent='parent_value', - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - authorization_policy_id='authorization_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].authorization_policy - mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') - assert arg == mock_val - arg = args[0].authorization_policy_id - mock_val = 'authorization_policy_id_value' - assert arg == mock_val - - -def test_create_authorization_policy_flattened_error(): - client = NetworkSecurityClient( - 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_authorization_policy( - gcn_authorization_policy.CreateAuthorizationPolicyRequest(), - parent='parent_value', - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - authorization_policy_id='authorization_policy_id_value', - ) - -@pytest.mark.asyncio -async def test_create_authorization_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_authorization_policy( - parent='parent_value', - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - authorization_policy_id='authorization_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].authorization_policy - mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') - assert arg == mock_val - arg = args[0].authorization_policy_id - mock_val = 'authorization_policy_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_authorization_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_authorization_policy( - gcn_authorization_policy.CreateAuthorizationPolicyRequest(), - parent='parent_value', - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - authorization_policy_id='authorization_policy_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_authorization_policy.UpdateAuthorizationPolicyRequest, - dict, -]) -def test_update_authorization_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_authorization_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_authorization_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_authorization_policy.UpdateAuthorizationPolicyRequest( - ) - -def test_update_authorization_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_authorization_policy] = mock_rpc - request = {} - client.update_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_authorization_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_authorization_policy] = mock_rpc - - request = {} - await client.update_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_authorization_policy.UpdateAuthorizationPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_authorization_policy_async_from_dict(): - await test_update_authorization_policy_async(request_type=dict) - -def test_update_authorization_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - - request.authorization_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_authorization_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', - 'authorization_policy.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_authorization_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - - request.authorization_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_authorization_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', - 'authorization_policy.name=name_value', - ) in kw['metadata'] - - -def test_update_authorization_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_authorization_policy( - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].authorization_policy - mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_authorization_policy_flattened_error(): - client = NetworkSecurityClient( - 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_authorization_policy( - gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_authorization_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_authorization_policy( - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].authorization_policy - mock_val = gcn_authorization_policy.AuthorizationPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_authorization_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_authorization_policy( - gcn_authorization_policy.UpdateAuthorizationPolicyRequest(), - authorization_policy=gcn_authorization_policy.AuthorizationPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - authorization_policy.DeleteAuthorizationPolicyRequest, - dict, -]) -def test_delete_authorization_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = authorization_policy.DeleteAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_authorization_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = authorization_policy.DeleteAuthorizationPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_authorization_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == authorization_policy.DeleteAuthorizationPolicyRequest( - name='name_value', - ) - -def test_delete_authorization_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_authorization_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_authorization_policy] = mock_rpc - request = {} - client.delete_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_authorization_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_authorization_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_authorization_policy] = mock_rpc - - request = {} - await client.delete_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_authorization_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_authorization_policy_async(transport: str = 'grpc_asyncio', request_type=authorization_policy.DeleteAuthorizationPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_authorization_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = authorization_policy.DeleteAuthorizationPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_authorization_policy_async_from_dict(): - await test_delete_authorization_policy_async(request_type=dict) - -def test_delete_authorization_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.DeleteAuthorizationPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_authorization_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_authorization_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = authorization_policy.DeleteAuthorizationPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_authorization_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_authorization_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_authorization_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_authorization_policy_flattened_error(): - client = NetworkSecurityClient( - 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_authorization_policy( - authorization_policy.DeleteAuthorizationPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_authorization_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_authorization_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_authorization_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_authorization_policy( - authorization_policy.DeleteAuthorizationPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - server_tls_policy.ListServerTlsPoliciesRequest, - dict, -]) -def test_list_server_tls_policies(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_server_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = server_tls_policy.ListServerTlsPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServerTlsPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_server_tls_policies_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = server_tls_policy.ListServerTlsPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_server_tls_policies(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == server_tls_policy.ListServerTlsPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_server_tls_policies_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_server_tls_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_server_tls_policies] = mock_rpc - request = {} - client.list_server_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_server_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_server_tls_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_server_tls_policies in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_server_tls_policies] = mock_rpc - - request = {} - await client.list_server_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_server_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_server_tls_policies_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.ListServerTlsPoliciesRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_server_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = server_tls_policy.ListServerTlsPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServerTlsPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_server_tls_policies_async_from_dict(): - await test_list_server_tls_policies_async(request_type=dict) - -def test_list_server_tls_policies_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.ListServerTlsPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() - client.list_server_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_server_tls_policies_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.ListServerTlsPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse()) - await client.list_server_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_server_tls_policies_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_server_tls_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_server_tls_policies_flattened_error(): - client = NetworkSecurityClient( - 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_server_tls_policies( - server_tls_policy.ListServerTlsPoliciesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_server_tls_policies_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_server_tls_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_server_tls_policies_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_server_tls_policies( - server_tls_policy.ListServerTlsPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_server_tls_policies_pager(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='abc', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[], - next_page_token='def', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='ghi', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_server_tls_policies(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) - for i in results) -def test_list_server_tls_policies_pages(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='abc', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[], - next_page_token='def', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='ghi', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_server_tls_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_list_server_tls_policies_async_pager(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='abc', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[], - next_page_token='def', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='ghi', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_server_tls_policies(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, server_tls_policy.ServerTlsPolicy) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_server_tls_policies_async_pages(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='abc', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[], - next_page_token='def', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - ], - next_page_token='ghi', - ), - server_tls_policy.ListServerTlsPoliciesResponse( - server_tls_policies=[ - server_tls_policy.ServerTlsPolicy(), - server_tls_policy.ServerTlsPolicy(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_server_tls_policies(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - server_tls_policy.GetServerTlsPolicyRequest, - dict, -]) -def test_get_server_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ServerTlsPolicy( - name='name_value', - description='description_value', - allow_open=True, - ) - response = client.get_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = server_tls_policy.GetServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, server_tls_policy.ServerTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.allow_open is True - - -def test_get_server_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = server_tls_policy.GetServerTlsPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_server_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == server_tls_policy.GetServerTlsPolicyRequest( - name='name_value', - ) - -def test_get_server_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_server_tls_policy] = mock_rpc - request = {} - client.get_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_server_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_server_tls_policy] = mock_rpc - - request = {} - await client.get_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.GetServerTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy( - name='name_value', - description='description_value', - allow_open=True, - )) - response = await client.get_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = server_tls_policy.GetServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, server_tls_policy.ServerTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.allow_open is True - - -@pytest.mark.asyncio -async def test_get_server_tls_policy_async_from_dict(): - await test_get_server_tls_policy_async(request_type=dict) - -def test_get_server_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.GetServerTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - call.return_value = server_tls_policy.ServerTlsPolicy() - client.get_server_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_server_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.GetServerTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy()) - await client.get_server_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_server_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ServerTlsPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_server_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_server_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_server_tls_policy( - server_tls_policy.GetServerTlsPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_server_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = server_tls_policy.ServerTlsPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_server_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_server_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_server_tls_policy( - server_tls_policy.GetServerTlsPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_server_tls_policy.CreateServerTlsPolicyRequest, - dict, -]) -def test_create_server_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_server_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest( - parent='parent_value', - server_tls_policy_id='server_tls_policy_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_server_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_server_tls_policy.CreateServerTlsPolicyRequest( - parent='parent_value', - server_tls_policy_id='server_tls_policy_id_value', - ) - -def test_create_server_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_server_tls_policy] = mock_rpc - request = {} - client.create_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_server_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_server_tls_policy] = mock_rpc - - request = {} - await client.create_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_server_tls_policy.CreateServerTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_server_tls_policy_async_from_dict(): - await test_create_server_tls_policy_async(request_type=dict) - -def test_create_server_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_server_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_server_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_server_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_server_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_server_tls_policy( - parent='parent_value', - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - server_tls_policy_id='server_tls_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].server_tls_policy - mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].server_tls_policy_id - mock_val = 'server_tls_policy_id_value' - assert arg == mock_val - - -def test_create_server_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_server_tls_policy( - gcn_server_tls_policy.CreateServerTlsPolicyRequest(), - parent='parent_value', - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - server_tls_policy_id='server_tls_policy_id_value', - ) - -@pytest.mark.asyncio -async def test_create_server_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_server_tls_policy( - parent='parent_value', - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - server_tls_policy_id='server_tls_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].server_tls_policy - mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].server_tls_policy_id - mock_val = 'server_tls_policy_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_server_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_server_tls_policy( - gcn_server_tls_policy.CreateServerTlsPolicyRequest(), - parent='parent_value', - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - server_tls_policy_id='server_tls_policy_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_server_tls_policy.UpdateServerTlsPolicyRequest, - dict, -]) -def test_update_server_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_server_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_server_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_server_tls_policy.UpdateServerTlsPolicyRequest( - ) - -def test_update_server_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_server_tls_policy] = mock_rpc - request = {} - client.update_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_server_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_server_tls_policy] = mock_rpc - - request = {} - await client.update_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_server_tls_policy.UpdateServerTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_server_tls_policy_async_from_dict(): - await test_update_server_tls_policy_async(request_type=dict) - -def test_update_server_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - - request.server_tls_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_server_tls_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', - 'server_tls_policy.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_server_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - - request.server_tls_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_server_tls_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', - 'server_tls_policy.name=name_value', - ) in kw['metadata'] - - -def test_update_server_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_server_tls_policy( - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].server_tls_policy - mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_server_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_server_tls_policy( - gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_server_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_server_tls_policy( - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].server_tls_policy - mock_val = gcn_server_tls_policy.ServerTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_server_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_server_tls_policy( - gcn_server_tls_policy.UpdateServerTlsPolicyRequest(), - server_tls_policy=gcn_server_tls_policy.ServerTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - server_tls_policy.DeleteServerTlsPolicyRequest, - dict, -]) -def test_delete_server_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = server_tls_policy.DeleteServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_server_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = server_tls_policy.DeleteServerTlsPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_server_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == server_tls_policy.DeleteServerTlsPolicyRequest( - name='name_value', - ) - -def test_delete_server_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_server_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_server_tls_policy] = mock_rpc - request = {} - client.delete_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_server_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_server_tls_policy] = mock_rpc - - request = {} - await client.delete_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_server_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_async(transport: str = 'grpc_asyncio', request_type=server_tls_policy.DeleteServerTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_server_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = server_tls_policy.DeleteServerTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_async_from_dict(): - await test_delete_server_tls_policy_async(request_type=dict) - -def test_delete_server_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.DeleteServerTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_server_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = server_tls_policy.DeleteServerTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_server_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_server_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_server_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_server_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_server_tls_policy( - server_tls_policy.DeleteServerTlsPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_server_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_server_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_server_tls_policy( - server_tls_policy.DeleteServerTlsPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.ListClientTlsPoliciesRequest, - dict, -]) -def test_list_client_tls_policies(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = client_tls_policy.ListClientTlsPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClientTlsPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_client_tls_policies_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = client_tls_policy.ListClientTlsPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_client_tls_policies(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == client_tls_policy.ListClientTlsPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_client_tls_policies_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_client_tls_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_client_tls_policies] = mock_rpc - request = {} - client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_client_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_client_tls_policies in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_client_tls_policies] = mock_rpc - - request = {} - await client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_client_tls_policies(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.ListClientTlsPoliciesRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_client_tls_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = client_tls_policy.ListClientTlsPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClientTlsPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async_from_dict(): - await test_list_client_tls_policies_async(request_type=dict) - -def test_list_client_tls_policies_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.ListClientTlsPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - client.list_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_client_tls_policies_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.ListClientTlsPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) - await client.list_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_client_tls_policies_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_client_tls_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_client_tls_policies_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policies( - client_tls_policy.ListClientTlsPoliciesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_client_tls_policies_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_client_tls_policies( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_client_tls_policies_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_client_tls_policies( - client_tls_policy.ListClientTlsPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_client_tls_policies_pager(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_client_tls_policies(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) - for i in results) -def test_list_client_tls_policies_pages(transport_name: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_client_tls_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_list_client_tls_policies_async_pager(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_client_tls_policies(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, client_tls_policy.ClientTlsPolicy) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_client_tls_policies_async_pages(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='abc', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[], - next_page_token='def', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - ], - next_page_token='ghi', - ), - client_tls_policy.ListClientTlsPoliciesResponse( - client_tls_policies=[ - client_tls_policy.ClientTlsPolicy(), - client_tls_policy.ClientTlsPolicy(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_client_tls_policies(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.GetClientTlsPolicyRequest, - dict, -]) -def test_get_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - ) - response = client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = client_tls_policy.GetClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, client_tls_policy.ClientTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.sni == 'sni_value' - - -def test_get_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = client_tls_policy.GetClientTlsPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == client_tls_policy.GetClientTlsPolicyRequest( - name='name_value', - ) - -def test_get_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_client_tls_policy] = mock_rpc - request = {} - client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_client_tls_policy] = mock_rpc - - request = {} - await client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.GetClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - )) - response = await client.get_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = client_tls_policy.GetClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, client_tls_policy.ClientTlsPolicy) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.sni == 'sni_value' - - -@pytest.mark.asyncio -async def test_get_client_tls_policy_async_from_dict(): - await test_get_client_tls_policy_async(request_type=dict) - -def test_get_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.GetClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value = client_tls_policy.ClientTlsPolicy() - client.get_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.GetClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) - await client.get_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ClientTlsPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - client_tls_policy.GetClientTlsPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = client_tls_policy.ClientTlsPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_client_tls_policy( - client_tls_policy.GetClientTlsPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_client_tls_policy.CreateClientTlsPolicyRequest, - dict, -]) -def test_create_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest( - parent='parent_value', - client_tls_policy_id='client_tls_policy_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_client_tls_policy.CreateClientTlsPolicyRequest( - parent='parent_value', - client_tls_policy_id='client_tls_policy_id_value', - ) - -def test_create_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_client_tls_policy] = mock_rpc - request = {} - client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_client_tls_policy] = mock_rpc - - request = {} - await client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.CreateClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_client_tls_policy_async_from_dict(): - await test_create_client_tls_policy_async(request_type=dict) - -def test_create_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_client_tls_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_client_tls_policy( - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].client_tls_policy_id - mock_val = 'client_tls_policy_id_value' - assert arg == mock_val - - -def test_create_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - gcn_client_tls_policy.CreateClientTlsPolicyRequest(), - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - -@pytest.mark.asyncio -async def test_create_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_client_tls_policy( - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].client_tls_policy_id - mock_val = 'client_tls_policy_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_client_tls_policy( - gcn_client_tls_policy.CreateClientTlsPolicyRequest(), - parent='parent_value', - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - client_tls_policy_id='client_tls_policy_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gcn_client_tls_policy.UpdateClientTlsPolicyRequest, - dict, -]) -def test_update_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gcn_client_tls_policy.UpdateClientTlsPolicyRequest( - ) - -def test_update_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_client_tls_policy] = mock_rpc - request = {} - client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_client_tls_policy] = mock_rpc - - request = {} - await client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=gcn_client_tls_policy.UpdateClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_client_tls_policy_async_from_dict(): - await test_update_client_tls_policy_async(request_type=dict) - -def test_update_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - request.client_tls_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_client_tls_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', - 'client_tls_policy.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - request.client_tls_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_client_tls_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', - 'client_tls_policy.name=name_value', - ) in kw['metadata'] - - -def test_update_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_client_tls_policy( - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_client_tls_policy( - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].client_tls_policy - mock_val = gcn_client_tls_policy.ClientTlsPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_client_tls_policy( - gcn_client_tls_policy.UpdateClientTlsPolicyRequest(), - client_tls_policy=gcn_client_tls_policy.ClientTlsPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - client_tls_policy.DeleteClientTlsPolicyRequest, - dict, -]) -def test_delete_client_tls_policy(request_type, transport: str = 'grpc'): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = client_tls_policy.DeleteClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_client_tls_policy_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = client_tls_policy.DeleteClientTlsPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_client_tls_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == client_tls_policy.DeleteClientTlsPolicyRequest( - name='name_value', - ) - -def test_delete_client_tls_policy_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_client_tls_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_client_tls_policy] = mock_rpc - request = {} - client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_client_tls_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_client_tls_policy] = mock_rpc - - request = {} - await client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_client_tls_policy(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_async(transport: str = 'grpc_asyncio', request_type=client_tls_policy.DeleteClientTlsPolicyRequest): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_client_tls_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = client_tls_policy.DeleteClientTlsPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_async_from_dict(): - await test_delete_client_tls_policy_async(request_type=dict) - -def test_delete_client_tls_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.DeleteClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = client_tls_policy.DeleteClientTlsPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_client_tls_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_client_tls_policy_flattened(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_client_tls_policy_flattened_error(): - client = NetworkSecurityClient( - 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_client_tls_policy( - client_tls_policy.DeleteClientTlsPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_flattened_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_client_tls_policy( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_client_tls_policy_flattened_error_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_client_tls_policy( - client_tls_policy.DeleteClientTlsPolicyRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = NetworkSecurityClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = NetworkSecurityClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.NetworkSecurityGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.NetworkSecurityGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.NetworkSecurityGrpcTransport, - transports.NetworkSecurityGrpcAsyncIOTransport, -]) -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_kind_grpc(): - transport = NetworkSecurityClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_authorization_policies_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - call.return_value = authorization_policy.ListAuthorizationPoliciesResponse() - client.list_authorization_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.ListAuthorizationPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_authorization_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - call.return_value = authorization_policy.AuthorizationPolicy() - client.get_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.GetAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_authorization_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_authorization_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_authorization_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_server_tls_policies_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - call.return_value = server_tls_policy.ListServerTlsPoliciesResponse() - client.list_server_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.ListServerTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_server_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - call.return_value = server_tls_policy.ServerTlsPolicy() - client.get_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.GetServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_server_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_server_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_server_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_client_tls_policies_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - call.return_value = client_tls_policy.ListClientTlsPoliciesResponse() - client.list_client_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.ListClientTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - call.return_value = client_tls_policy.ClientTlsPolicy() - client.get_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.GetClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_client_tls_policy_empty_call_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = NetworkSecurityAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_authorization_policies_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_authorization_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.ListAuthorizationPoliciesResponse( - next_page_token='next_page_token_value', - )) - await client.list_authorization_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.ListAuthorizationPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(authorization_policy.AuthorizationPolicy( - name='name_value', - description='description_value', - action=authorization_policy.AuthorizationPolicy.Action.ALLOW, - )) - await client.get_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.GetAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.CreateAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_authorization_policy.UpdateAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_authorization_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_authorization_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_authorization_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = authorization_policy.DeleteAuthorizationPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_server_tls_policies_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_server_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ListServerTlsPoliciesResponse( - next_page_token='next_page_token_value', - )) - await client.list_server_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.ListServerTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(server_tls_policy.ServerTlsPolicy( - name='name_value', - description='description_value', - allow_open=True, - )) - await client.get_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.GetServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.CreateServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_server_tls_policy.UpdateServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_server_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_server_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_server_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = server_tls_policy.DeleteServerTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_client_tls_policies_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_client_tls_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ListClientTlsPoliciesResponse( - next_page_token='next_page_token_value', - )) - await client.list_client_tls_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.ListClientTlsPoliciesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(client_tls_policy.ClientTlsPolicy( - name='name_value', - description='description_value', - sni='sni_value', - )) - await client.get_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.GetClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.CreateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gcn_client_tls_policy.UpdateClientTlsPolicyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_client_tls_policy_empty_call_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_client_tls_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_client_tls_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = client_tls_policy.DeleteClientTlsPolicyRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.NetworkSecurityGrpcTransport, - ) - -def test_network_security_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.NetworkSecurityTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_network_security_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.network_security_v1beta1.services.network_security.transports.NetworkSecurityTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.NetworkSecurityTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_authorization_policies', - 'get_authorization_policy', - 'create_authorization_policy', - 'update_authorization_policy', - 'delete_authorization_policy', - 'list_server_tls_policies', - 'get_server_tls_policy', - 'create_server_tls_policy', - 'update_server_tls_policy', - 'delete_server_tls_policy', - 'list_client_tls_policies', - 'get_client_tls_policy', - 'create_client_tls_policy', - 'update_client_tls_policy', - 'delete_client_tls_policy', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_network_security_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.network_security_v1beta1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.NetworkSecurityTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_network_security_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.network_security_v1beta1.services.network_security.transports.NetworkSecurityTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.NetworkSecurityTransport() - adc.assert_called_once() - - -def test_network_security_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) - NetworkSecurityClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.NetworkSecurityGrpcTransport, - transports.NetworkSecurityGrpcAsyncIOTransport, - ], -) -def test_network_security_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.NetworkSecurityGrpcTransport, - transports.NetworkSecurityGrpcAsyncIOTransport, - ], -) -def test_network_security_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.NetworkSecurityGrpcTransport, grpc_helpers), - (transports.NetworkSecurityGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_network_security_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( - "networksecurity.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="networksecurity.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) -def test_network_security_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_network_security_host_no_port(transport_name): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", -]) -def test_network_security_host_with_port(transport_name): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'networksecurity.googleapis.com:8000' - ) - -def test_network_security_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.NetworkSecurityGrpcTransport( - 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_network_security_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.NetworkSecurityGrpcAsyncIOTransport( - 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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) -def test_network_security_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.NetworkSecurityGrpcTransport, transports.NetworkSecurityGrpcAsyncIOTransport]) -def test_network_security_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_network_security_grpc_lro_client(): - client = NetworkSecurityClient( - 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_network_security_grpc_lro_async_client(): - client = NetworkSecurityAsyncClient( - 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_authorization_policy_path(): - project = "squid" - location = "clam" - authorization_policy = "whelk" - expected = "projects/{project}/locations/{location}/authorizationPolicies/{authorization_policy}".format(project=project, location=location, authorization_policy=authorization_policy, ) - actual = NetworkSecurityClient.authorization_policy_path(project, location, authorization_policy) - assert expected == actual - - -def test_parse_authorization_policy_path(): - expected = { - "project": "octopus", - "location": "oyster", - "authorization_policy": "nudibranch", - } - path = NetworkSecurityClient.authorization_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_authorization_policy_path(path) - assert expected == actual - -def test_client_tls_policy_path(): - project = "cuttlefish" - location = "mussel" - client_tls_policy = "winkle" - expected = "projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}".format(project=project, location=location, client_tls_policy=client_tls_policy, ) - actual = NetworkSecurityClient.client_tls_policy_path(project, location, client_tls_policy) - assert expected == actual - - -def test_parse_client_tls_policy_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "client_tls_policy": "abalone", - } - path = NetworkSecurityClient.client_tls_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_client_tls_policy_path(path) - assert expected == actual - -def test_server_tls_policy_path(): - project = "squid" - location = "clam" - server_tls_policy = "whelk" - expected = "projects/{project}/locations/{location}/serverTlsPolicies/{server_tls_policy}".format(project=project, location=location, server_tls_policy=server_tls_policy, ) - actual = NetworkSecurityClient.server_tls_policy_path(project, location, server_tls_policy) - assert expected == actual - - -def test_parse_server_tls_policy_path(): - expected = { - "project": "octopus", - "location": "oyster", - "server_tls_policy": "nudibranch", - } - path = NetworkSecurityClient.server_tls_policy_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_server_tls_policy_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = NetworkSecurityClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = NetworkSecurityClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = NetworkSecurityClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = NetworkSecurityClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = NetworkSecurityClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = NetworkSecurityClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = NetworkSecurityClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = NetworkSecurityClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = NetworkSecurityClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = NetworkSecurityClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = NetworkSecurityClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.NetworkSecurityTransport, '_prep_wrapped_messages') as prep: - transport_class = NetworkSecurityClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_delete_operation(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None - - client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_delete_operation_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_delete_operation_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = operations_pb2.ListOperationsResponse() - - client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = NetworkSecurityAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'grpc', - ] - for transport in transports: - client = NetworkSecurityClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (NetworkSecurityClient, transports.NetworkSecurityGrpcTransport), - (NetworkSecurityAsyncClient, transports.NetworkSecurityGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/address_group_service.rst b/packages/google-cloud-network-security/docs/network_security_v1/address_group_service.rst similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/address_group_service.rst rename to packages/google-cloud-network-security/docs/network_security_v1/address_group_service.rst diff --git a/owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/organization_address_group_service.rst b/packages/google-cloud-network-security/docs/network_security_v1/organization_address_group_service.rst similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/docs/network_security_v1/organization_address_group_service.rst rename to packages/google-cloud-network-security/docs/network_security_v1/organization_address_group_service.rst diff --git a/packages/google-cloud-network-security/docs/network_security_v1/services_.rst b/packages/google-cloud-network-security/docs/network_security_v1/services_.rst index 3dadbd0d8a0f..a78574643ed1 100644 --- a/packages/google-cloud-network-security/docs/network_security_v1/services_.rst +++ b/packages/google-cloud-network-security/docs/network_security_v1/services_.rst @@ -3,4 +3,6 @@ Services for Google Cloud Network Security v1 API .. toctree:: :maxdepth: 2 + address_group_service network_security + organization_address_group_service diff --git a/packages/google-cloud-network-security/google/cloud/network_security/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security/__init__.py index 0fa40d4dc724..ea6769c035df 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security/__init__.py @@ -18,12 +18,38 @@ __version__ = package_version.__version__ +from google.cloud.network_security_v1.services.address_group_service.async_client import ( + AddressGroupServiceAsyncClient, +) +from google.cloud.network_security_v1.services.address_group_service.client import ( + AddressGroupServiceClient, +) from google.cloud.network_security_v1.services.network_security.async_client import ( NetworkSecurityAsyncClient, ) from google.cloud.network_security_v1.services.network_security.client import ( NetworkSecurityClient, ) +from google.cloud.network_security_v1.services.organization_address_group_service.async_client import ( + OrganizationAddressGroupServiceAsyncClient, +) +from google.cloud.network_security_v1.services.organization_address_group_service.client import ( + OrganizationAddressGroupServiceClient, +) +from google.cloud.network_security_v1.types.address_group import ( + AddAddressGroupItemsRequest, + AddressGroup, + CloneAddressGroupItemsRequest, + CreateAddressGroupRequest, + DeleteAddressGroupRequest, + GetAddressGroupRequest, + ListAddressGroupReferencesRequest, + ListAddressGroupReferencesResponse, + ListAddressGroupsRequest, + ListAddressGroupsResponse, + RemoveAddressGroupItemsRequest, + UpdateAddressGroupRequest, +) from google.cloud.network_security_v1.types.authorization_policy import ( AuthorizationPolicy, CreateAuthorizationPolicyRequest, @@ -60,8 +86,24 @@ ) __all__ = ( + "AddressGroupServiceClient", + "AddressGroupServiceAsyncClient", "NetworkSecurityClient", "NetworkSecurityAsyncClient", + "OrganizationAddressGroupServiceClient", + "OrganizationAddressGroupServiceAsyncClient", + "AddAddressGroupItemsRequest", + "AddressGroup", + "CloneAddressGroupItemsRequest", + "CreateAddressGroupRequest", + "DeleteAddressGroupRequest", + "GetAddressGroupRequest", + "ListAddressGroupReferencesRequest", + "ListAddressGroupReferencesResponse", + "ListAddressGroupsRequest", + "ListAddressGroupsResponse", + "RemoveAddressGroupItemsRequest", + "UpdateAddressGroupRequest", "AuthorizationPolicy", "CreateAuthorizationPolicyRequest", "DeleteAuthorizationPolicyRequest", diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/__init__.py index 3afd7e1db1f2..660432779fe0 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/__init__.py @@ -18,7 +18,29 @@ __version__ = package_version.__version__ +from .services.address_group_service import ( + AddressGroupServiceAsyncClient, + AddressGroupServiceClient, +) from .services.network_security import NetworkSecurityAsyncClient, NetworkSecurityClient +from .services.organization_address_group_service import ( + OrganizationAddressGroupServiceAsyncClient, + OrganizationAddressGroupServiceClient, +) +from .types.address_group import ( + AddAddressGroupItemsRequest, + AddressGroup, + CloneAddressGroupItemsRequest, + CreateAddressGroupRequest, + DeleteAddressGroupRequest, + GetAddressGroupRequest, + ListAddressGroupReferencesRequest, + ListAddressGroupReferencesResponse, + ListAddressGroupsRequest, + ListAddressGroupsResponse, + RemoveAddressGroupItemsRequest, + UpdateAddressGroupRequest, +) from .types.authorization_policy import ( AuthorizationPolicy, CreateAuthorizationPolicyRequest, @@ -55,21 +77,34 @@ ) __all__ = ( + "AddressGroupServiceAsyncClient", "NetworkSecurityAsyncClient", + "OrganizationAddressGroupServiceAsyncClient", + "AddAddressGroupItemsRequest", + "AddressGroup", + "AddressGroupServiceClient", "AuthorizationPolicy", "CertificateProvider", "CertificateProviderInstance", "ClientTlsPolicy", + "CloneAddressGroupItemsRequest", + "CreateAddressGroupRequest", "CreateAuthorizationPolicyRequest", "CreateClientTlsPolicyRequest", "CreateServerTlsPolicyRequest", + "DeleteAddressGroupRequest", "DeleteAuthorizationPolicyRequest", "DeleteClientTlsPolicyRequest", "DeleteServerTlsPolicyRequest", + "GetAddressGroupRequest", "GetAuthorizationPolicyRequest", "GetClientTlsPolicyRequest", "GetServerTlsPolicyRequest", "GrpcEndpoint", + "ListAddressGroupReferencesRequest", + "ListAddressGroupReferencesResponse", + "ListAddressGroupsRequest", + "ListAddressGroupsResponse", "ListAuthorizationPoliciesRequest", "ListAuthorizationPoliciesResponse", "ListClientTlsPoliciesRequest", @@ -78,7 +113,10 @@ "ListServerTlsPoliciesResponse", "NetworkSecurityClient", "OperationMetadata", + "OrganizationAddressGroupServiceClient", + "RemoveAddressGroupItemsRequest", "ServerTlsPolicy", + "UpdateAddressGroupRequest", "UpdateAuthorizationPolicyRequest", "UpdateClientTlsPolicyRequest", "UpdateServerTlsPolicyRequest", diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_metadata.json b/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_metadata.json index edaaf2fc5f59..7a369b0303ca 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_metadata.json +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/gapic_metadata.json @@ -5,6 +5,160 @@ "protoPackage": "google.cloud.networksecurity.v1", "schema": "1.0", "services": { + "AddressGroupService": { + "clients": { + "grpc": { + "libraryClient": "AddressGroupServiceClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AddressGroupServiceAsyncClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + }, + "rest": { + "libraryClient": "AddressGroupServiceClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + } + } + }, "NetworkSecurity": { "clients": { "grpc": { @@ -248,6 +402,160 @@ } } } + }, + "OrganizationAddressGroupService": { + "clients": { + "grpc": { + "libraryClient": "OrganizationAddressGroupServiceClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OrganizationAddressGroupServiceAsyncClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + }, + "rest": { + "libraryClient": "OrganizationAddressGroupServiceClient", + "rpcs": { + "AddAddressGroupItems": { + "methods": [ + "add_address_group_items" + ] + }, + "CloneAddressGroupItems": { + "methods": [ + "clone_address_group_items" + ] + }, + "CreateAddressGroup": { + "methods": [ + "create_address_group" + ] + }, + "DeleteAddressGroup": { + "methods": [ + "delete_address_group" + ] + }, + "GetAddressGroup": { + "methods": [ + "get_address_group" + ] + }, + "ListAddressGroupReferences": { + "methods": [ + "list_address_group_references" + ] + }, + "ListAddressGroups": { + "methods": [ + "list_address_groups" + ] + }, + "RemoveAddressGroupItems": { + "methods": [ + "remove_address_group_items" + ] + }, + "UpdateAddressGroup": { + "methods": [ + "update_address_group" + ] + } + } + } + } } } } diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/__init__.py similarity index 91% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/__init__.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/__init__.py index f100e3c88e55..40613297ab20 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import AddressGroupServiceClient from .async_client import AddressGroupServiceAsyncClient +from .client import AddressGroupServiceClient __all__ = ( - 'AddressGroupServiceClient', - 'AddressGroupServiceAsyncClient', + "AddressGroupServiceClient", + "AddressGroupServiceAsyncClient", ) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/async_client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/async_client.py similarity index 85% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/async_client.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/async_client.py index 163edd248829..43d3268b1e84 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/async_client.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/async_client.py @@ -13,21 +13,31 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging as std_logging from collections import OrderedDict +import logging as std_logging import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.network_security_v1 import gapic_version as package_version +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf +from google.cloud.network_security_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -36,29 +46,33 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.services.address_group_service import pagers -from google.cloud.network_security_v1.types import address_group -from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.cloud.network_security_v1.types import common +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import AddressGroupServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AddressGroupServiceGrpcAsyncIOTransport + +from google.cloud.network_security_v1.services.address_group_service import pagers +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import common + from .client import AddressGroupServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, AddressGroupServiceTransport +from .transports.grpc_asyncio import AddressGroupServiceGrpcAsyncIOTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class AddressGroupServiceAsyncClient: """AddressGroup is a resource that manages a collection of IP or Domain Names, it can be used in Firewall Policy to represent @@ -76,17 +90,33 @@ class AddressGroupServiceAsyncClient: _DEFAULT_UNIVERSE = AddressGroupServiceClient._DEFAULT_UNIVERSE address_group_path = staticmethod(AddressGroupServiceClient.address_group_path) - parse_address_group_path = staticmethod(AddressGroupServiceClient.parse_address_group_path) - common_billing_account_path = staticmethod(AddressGroupServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AddressGroupServiceClient.parse_common_billing_account_path) + parse_address_group_path = staticmethod( + AddressGroupServiceClient.parse_address_group_path + ) + common_billing_account_path = staticmethod( + AddressGroupServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AddressGroupServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(AddressGroupServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AddressGroupServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AddressGroupServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AddressGroupServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + AddressGroupServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + AddressGroupServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + AddressGroupServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(AddressGroupServiceClient.common_project_path) - parse_common_project_path = staticmethod(AddressGroupServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + AddressGroupServiceClient.parse_common_project_path + ) common_location_path = staticmethod(AddressGroupServiceClient.common_location_path) - parse_common_location_path = staticmethod(AddressGroupServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + AddressGroupServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -122,7 +152,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -185,12 +217,20 @@ def universe_domain(self) -> str: get_transport_class = AddressGroupServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AddressGroupServiceTransport, Callable[..., AddressGroupServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + AddressGroupServiceTransport, + Callable[..., AddressGroupServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the address group service async client. Args: @@ -245,31 +285,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "credentialsType": None, - } + }, ) - async def list_address_groups(self, - request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAddressGroupsAsyncPager: + async def list_address_groups( + self, + request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupsAsyncPager: r"""Lists address groups in a given project and location. .. code-block:: python @@ -332,10 +380,14 @@ async def sample_list_address_groups(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -349,14 +401,14 @@ async def sample_list_address_groups(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_address_groups] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_address_groups + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -384,14 +436,15 @@ async def sample_list_address_groups(): # Done; return the response. return response - async def get_address_group(self, - request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> address_group.AddressGroup: + async def get_address_group( + self, + request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.AddressGroup: r"""Gets details of a single address group. .. code-block:: python @@ -451,10 +504,14 @@ async def sample_get_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -468,14 +525,14 @@ async def sample_get_address_group(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_address_group] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_address_group + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -492,16 +549,19 @@ async def sample_get_address_group(): # Done; return the response. return response - async def create_address_group(self, - request: Optional[Union[gcn_address_group.CreateAddressGroupRequest, dict]] = None, - *, - parent: Optional[str] = None, - address_group: Optional[gcn_address_group.AddressGroup] = None, - address_group_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_address_group( + self, + request: Optional[ + Union[gcn_address_group.CreateAddressGroupRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + address_group: Optional[gcn_address_group.AddressGroup] = None, + address_group_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Creates a new address group in a given project and location. @@ -590,10 +650,14 @@ async def sample_create_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, address_group, address_group_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -611,14 +675,14 @@ async def sample_create_address_group(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_address_group] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_address_group + ] # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -643,15 +707,18 @@ async def sample_create_address_group(): # Done; return the response. return response - async def update_address_group(self, - request: Optional[Union[gcn_address_group.UpdateAddressGroupRequest, dict]] = None, - *, - address_group: Optional[gcn_address_group.AddressGroup] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_address_group( + self, + request: Optional[ + Union[gcn_address_group.UpdateAddressGroupRequest, dict] + ] = None, + *, + address_group: Optional[gcn_address_group.AddressGroup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Updates the parameters of a single address group. .. code-block:: python @@ -731,10 +798,14 @@ async def sample_update_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -750,14 +821,16 @@ async def sample_update_address_group(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_address_group] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_address_group + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group.name", request.address_group.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group.name", request.address_group.name),) + ), ) # Validate the universe domain. @@ -782,15 +855,18 @@ async def sample_update_address_group(): # Done; return the response. return response - async def add_address_group_items(self, - request: Optional[Union[gcn_address_group.AddAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - items: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def add_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.AddAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Adds items to an address group. .. code-block:: python @@ -861,10 +937,14 @@ async def sample_add_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, items] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -880,14 +960,16 @@ async def sample_add_address_group_items(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.add_address_group_items] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.add_address_group_items + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -912,15 +994,18 @@ async def sample_add_address_group_items(): # Done; return the response. return response - async def remove_address_group_items(self, - request: Optional[Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - items: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def remove_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Removes items from an address group. .. code-block:: python @@ -991,10 +1076,14 @@ async def sample_remove_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, items] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1010,14 +1099,16 @@ async def sample_remove_address_group_items(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.remove_address_group_items] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.remove_address_group_items + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1042,15 +1133,18 @@ async def sample_remove_address_group_items(): # Done; return the response. return response - async def clone_address_group_items(self, - request: Optional[Union[gcn_address_group.CloneAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - source_address_group: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def clone_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.CloneAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + source_address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Clones items from one address group to another. .. code-block:: python @@ -1123,10 +1217,14 @@ async def sample_clone_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, source_address_group] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1142,14 +1240,16 @@ async def sample_clone_address_group_items(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.clone_address_group_items] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.clone_address_group_items + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1174,14 +1274,15 @@ async def sample_clone_address_group_items(): # Done; return the response. return response - async def delete_address_group(self, - request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_address_group( + self, + request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Deletes a single address group. .. code-block:: python @@ -1254,10 +1355,14 @@ async def sample_delete_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1271,14 +1376,14 @@ async def sample_delete_address_group(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_address_group] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_address_group + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1303,14 +1408,17 @@ async def sample_delete_address_group(): # Done; return the response. return response - async def list_address_group_references(self, - request: Optional[Union[gcn_address_group.ListAddressGroupReferencesRequest, dict]] = None, - *, - address_group: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAddressGroupReferencesAsyncPager: + async def list_address_group_references( + self, + request: Optional[ + Union[gcn_address_group.ListAddressGroupReferencesRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupReferencesAsyncPager: r"""Lists references of an address group. .. code-block:: python @@ -1373,10 +1481,14 @@ async def sample_list_address_group_references(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1390,14 +1502,16 @@ async def sample_list_address_group_references(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_address_group_references] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_address_group_references + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1463,8 +1577,7 @@ async def list_operations( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1472,7 +1585,11 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1515,8 +1632,7 @@ async def get_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1524,7 +1640,11 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1571,15 +1691,19 @@ async def delete_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def cancel_operation( self, @@ -1622,15 +1746,19 @@ async def cancel_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def set_iam_policy( self, @@ -1736,8 +1864,7 @@ async def set_iam_policy( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -1745,7 +1872,11 @@ async def set_iam_policy( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1855,8 +1986,7 @@ async def get_iam_policy( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -1864,7 +1994,11 @@ async def get_iam_policy( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1907,13 +2041,14 @@ async def test_iam_permissions( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -1921,7 +2056,11 @@ async def test_iam_permissions( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1964,8 +2103,7 @@ async def get_location( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1973,7 +2111,11 @@ async def get_location( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2016,8 +2158,7 @@ async def list_locations( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2025,7 +2166,11 @@ async def list_locations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2036,12 +2181,13 @@ async def __aenter__(self) -> "AddressGroupServiceAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "AddressGroupServiceAsyncClient", -) +__all__ = ("AddressGroupServiceAsyncClient",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/client.py similarity index 84% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/client.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/client.py index a99a24c5547f..f12cef8da35b 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/client.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/client.py @@ -19,22 +19,34 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings -from google.cloud.network_security_v1 import gapic_version as package_version - from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf +from google.cloud.network_security_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -50,18 +63,20 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.services.address_group_service import pagers -from google.cloud.network_security_v1.types import address_group -from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.cloud.network_security_v1.types import common +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import AddressGroupServiceTransport, DEFAULT_CLIENT_INFO + +from google.cloud.network_security_v1.services.address_group_service import pagers +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import common + +from .transports.base import DEFAULT_CLIENT_INFO, AddressGroupServiceTransport from .transports.grpc import AddressGroupServiceGrpcTransport from .transports.grpc_asyncio import AddressGroupServiceGrpcAsyncIOTransport from .transports.rest import AddressGroupServiceRestTransport @@ -74,14 +89,18 @@ class AddressGroupServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[AddressGroupServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[AddressGroupServiceTransport]] _transport_registry["grpc"] = AddressGroupServiceGrpcTransport _transport_registry["grpc_asyncio"] = AddressGroupServiceGrpcAsyncIOTransport _transport_registry["rest"] = AddressGroupServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AddressGroupServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AddressGroupServiceTransport]: """Returns an appropriate transport class. Args: @@ -177,8 +196,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AddressGroupServiceClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -195,73 +213,108 @@ def transport(self) -> AddressGroupServiceTransport: return self._transport @staticmethod - def address_group_path(project: str,location: str,address_group: str,) -> str: + def address_group_path( + project: str, + location: str, + address_group: str, + ) -> str: """Returns a fully-qualified address_group string.""" - return "projects/{project}/locations/{location}/addressGroups/{address_group}".format(project=project, location=location, address_group=address_group, ) + return "projects/{project}/locations/{location}/addressGroups/{address_group}".format( + project=project, + location=location, + address_group=address_group, + ) @staticmethod - def parse_address_group_path(path: str) -> Dict[str,str]: + def parse_address_group_path(path: str) -> Dict[str, str]: """Parses a address_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/addressGroups/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/addressGroups/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + 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, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + 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: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + 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: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + 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: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -293,16 +346,22 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -315,7 +374,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -336,13 +397,19 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert == "true", use_mtls_endpoint, universe_domain_env @staticmethod @@ -365,7 +432,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): """Return the API endpoint used by the client. Args: @@ -381,17 +450,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = AddressGroupServiceClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -427,15 +504,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -468,12 +548,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AddressGroupServiceTransport, Callable[..., AddressGroupServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + AddressGroupServiceTransport, + Callable[..., AddressGroupServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the address group service client. Args: @@ -528,14 +616,24 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AddressGroupServiceClient._read_environment_variables() - self._client_cert_source = AddressGroupServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AddressGroupServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = AddressGroupServiceClient._read_environment_variables() + self._client_cert_source = AddressGroupServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = AddressGroupServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -546,7 +644,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -555,8 +655,10 @@ def __init__(self, *, if transport_provided: # transport is a AddressGroupServiceTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -565,20 +667,30 @@ def __init__(self, *, self._transport = cast(AddressGroupServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - AddressGroupServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or AddressGroupServiceClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[AddressGroupServiceTransport], Callable[..., AddressGroupServiceTransport]] = ( + transport_init: Union[ + Type[AddressGroupServiceTransport], + Callable[..., AddressGroupServiceTransport], + ] = ( AddressGroupServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., AddressGroupServiceTransport], transport) @@ -597,28 +709,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.networksecurity_v1.AddressGroupServiceClient`.", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "credentialsType": None, - } + }, ) - def list_address_groups(self, - request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAddressGroupsPager: + def list_address_groups( + self, + request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupsPager: r"""Lists address groups in a given project and location. .. code-block:: python @@ -681,10 +802,14 @@ def sample_list_address_groups(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -702,9 +827,7 @@ def sample_list_address_groups(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -732,14 +855,15 @@ def sample_list_address_groups(): # Done; return the response. return response - def get_address_group(self, - request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> address_group.AddressGroup: + def get_address_group( + self, + request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.AddressGroup: r"""Gets details of a single address group. .. code-block:: python @@ -799,10 +923,14 @@ def sample_get_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -820,9 +948,7 @@ def sample_get_address_group(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -839,16 +965,19 @@ def sample_get_address_group(): # Done; return the response. return response - def create_address_group(self, - request: Optional[Union[gcn_address_group.CreateAddressGroupRequest, dict]] = None, - *, - parent: Optional[str] = None, - address_group: Optional[gcn_address_group.AddressGroup] = None, - address_group_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_address_group( + self, + request: Optional[ + Union[gcn_address_group.CreateAddressGroupRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + address_group: Optional[gcn_address_group.AddressGroup] = None, + address_group_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a new address group in a given project and location. @@ -937,10 +1066,14 @@ def sample_create_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, address_group, address_group_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -962,9 +1095,7 @@ def sample_create_address_group(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -989,15 +1120,18 @@ def sample_create_address_group(): # Done; return the response. return response - def update_address_group(self, - request: Optional[Union[gcn_address_group.UpdateAddressGroupRequest, dict]] = None, - *, - address_group: Optional[gcn_address_group.AddressGroup] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_address_group( + self, + request: Optional[ + Union[gcn_address_group.UpdateAddressGroupRequest, dict] + ] = None, + *, + address_group: Optional[gcn_address_group.AddressGroup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates the parameters of a single address group. .. code-block:: python @@ -1077,10 +1211,14 @@ def sample_update_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1100,9 +1238,9 @@ def sample_update_address_group(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group.name", request.address_group.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group.name", request.address_group.name),) + ), ) # Validate the universe domain. @@ -1127,15 +1265,18 @@ def sample_update_address_group(): # Done; return the response. return response - def add_address_group_items(self, - request: Optional[Union[gcn_address_group.AddAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - items: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def add_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.AddAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Adds items to an address group. .. code-block:: python @@ -1206,10 +1347,14 @@ def sample_add_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, items] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1229,9 +1374,9 @@ def sample_add_address_group_items(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1256,15 +1401,18 @@ def sample_add_address_group_items(): # Done; return the response. return response - def remove_address_group_items(self, - request: Optional[Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - items: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def remove_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Removes items from an address group. .. code-block:: python @@ -1335,10 +1483,14 @@ def sample_remove_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, items] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1353,14 +1505,16 @@ def sample_remove_address_group_items(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_address_group_items] + rpc = self._transport._wrapped_methods[ + self._transport.remove_address_group_items + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1385,15 +1539,18 @@ def sample_remove_address_group_items(): # Done; return the response. return response - def clone_address_group_items(self, - request: Optional[Union[gcn_address_group.CloneAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - source_address_group: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def clone_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.CloneAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + source_address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Clones items from one address group to another. .. code-block:: python @@ -1466,10 +1623,14 @@ def sample_clone_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, source_address_group] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1484,14 +1645,16 @@ def sample_clone_address_group_items(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.clone_address_group_items] + rpc = self._transport._wrapped_methods[ + self._transport.clone_address_group_items + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1516,14 +1679,15 @@ def sample_clone_address_group_items(): # Done; return the response. return response - def delete_address_group(self, - request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_address_group( + self, + request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes a single address group. .. code-block:: python @@ -1596,10 +1760,14 @@ def sample_delete_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1617,9 +1785,7 @@ def sample_delete_address_group(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1644,14 +1810,17 @@ def sample_delete_address_group(): # Done; return the response. return response - def list_address_group_references(self, - request: Optional[Union[gcn_address_group.ListAddressGroupReferencesRequest, dict]] = None, - *, - address_group: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAddressGroupReferencesPager: + def list_address_group_references( + self, + request: Optional[ + Union[gcn_address_group.ListAddressGroupReferencesRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupReferencesPager: r"""Lists references of an address group. .. code-block:: python @@ -1714,10 +1883,14 @@ def sample_list_address_group_references(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1730,14 +1903,16 @@ def sample_list_address_group_references(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_address_group_references] + rpc = self._transport._wrapped_methods[ + self._transport.list_address_group_references + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1816,8 +1991,7 @@ def list_operations( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1826,7 +2000,11 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1872,8 +2050,7 @@ def get_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1882,7 +2059,11 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1932,15 +2113,19 @@ def delete_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def cancel_operation( self, @@ -1983,15 +2168,19 @@ def cancel_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def set_iam_policy( self, @@ -2097,8 +2286,7 @@ def set_iam_policy( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -2107,7 +2295,11 @@ def set_iam_policy( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2220,8 +2412,7 @@ def get_iam_policy( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -2230,7 +2421,11 @@ def get_iam_policy( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2281,8 +2476,7 @@ def test_iam_permissions( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -2291,7 +2485,11 @@ def test_iam_permissions( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2337,8 +2535,7 @@ def get_location( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2347,7 +2544,11 @@ def get_location( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2393,8 +2594,7 @@ def list_locations( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2403,7 +2603,11 @@ def list_locations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2412,11 +2616,11 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "AddressGroupServiceClient", -) +__all__ = ("AddressGroupServiceClient",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/pagers.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/pagers.py similarity index 76% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/pagers.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/pagers.py index 4c8ac9f092ff..1798baeb1630 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/pagers.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/pagers.py @@ -13,19 +13,33 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore -from google.cloud.network_security_v1.types import address_group from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import address_group class ListAddressGroupsPager: @@ -45,14 +59,17 @@ class ListAddressGroupsPager: 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[..., address_group.ListAddressGroupsResponse], - request: address_group.ListAddressGroupsRequest, - response: address_group.ListAddressGroupsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + + def __init__( + self, + method: Callable[..., address_group.ListAddressGroupsResponse], + request: address_group.ListAddressGroupsRequest, + response: address_group.ListAddressGroupsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): """Instantiate the pager. Args: @@ -85,7 +102,12 @@ def pages(self) -> Iterator[address_group.ListAddressGroupsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) yield self._response def __iter__(self) -> Iterator[address_group.AddressGroup]: @@ -93,7 +115,7 @@ def __iter__(self) -> Iterator[address_group.AddressGroup]: yield from page.address_groups def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListAddressGroupsAsyncPager: @@ -113,14 +135,17 @@ class ListAddressGroupsAsyncPager: 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[address_group.ListAddressGroupsResponse]], - request: address_group.ListAddressGroupsRequest, - response: address_group.ListAddressGroupsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + + def __init__( + self, + method: Callable[..., Awaitable[address_group.ListAddressGroupsResponse]], + request: address_group.ListAddressGroupsRequest, + response: address_group.ListAddressGroupsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): """Instantiates the pager. Args: @@ -153,8 +178,14 @@ async def pages(self) -> AsyncIterator[address_group.ListAddressGroupsResponse]: 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) yield self._response + def __aiter__(self) -> AsyncIterator[address_group.AddressGroup]: async def async_generator(): async for page in self.pages: @@ -164,7 +195,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListAddressGroupReferencesPager: @@ -184,14 +215,17 @@ class ListAddressGroupReferencesPager: 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[..., gcn_address_group.ListAddressGroupReferencesResponse], - request: gcn_address_group.ListAddressGroupReferencesRequest, - response: gcn_address_group.ListAddressGroupReferencesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + + def __init__( + self, + method: Callable[..., gcn_address_group.ListAddressGroupReferencesResponse], + request: gcn_address_group.ListAddressGroupReferencesRequest, + response: gcn_address_group.ListAddressGroupReferencesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): """Instantiate the pager. Args: @@ -224,15 +258,24 @@ def pages(self) -> Iterator[gcn_address_group.ListAddressGroupReferencesResponse yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) yield self._response - def __iter__(self) -> Iterator[gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference]: + def __iter__( + self, + ) -> Iterator[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference + ]: for page in self.pages: yield from page.address_group_references def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListAddressGroupReferencesAsyncPager: @@ -252,14 +295,19 @@ class ListAddressGroupReferencesAsyncPager: 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[gcn_address_group.ListAddressGroupReferencesResponse]], - request: gcn_address_group.ListAddressGroupReferencesRequest, - response: gcn_address_group.ListAddressGroupReferencesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + + def __init__( + self, + method: Callable[ + ..., Awaitable[gcn_address_group.ListAddressGroupReferencesResponse] + ], + request: gcn_address_group.ListAddressGroupReferencesRequest, + response: gcn_address_group.ListAddressGroupReferencesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): """Instantiates the pager. Args: @@ -288,13 +336,25 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages(self) -> AsyncIterator[gcn_address_group.ListAddressGroupReferencesResponse]: + async def pages( + self, + ) -> AsyncIterator[gcn_address_group.ListAddressGroupReferencesResponse]: 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) yield self._response - def __aiter__(self) -> AsyncIterator[gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference]: + + def __aiter__( + self, + ) -> AsyncIterator[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference + ]: async def async_generator(): async for page in self.pages: for response in page.address_group_references: @@ -303,4 +363,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/README.rst b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/README.rst rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/README.rst diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py similarity index 60% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py index cea017c338fc..ab668b3c302c 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/__init__.py @@ -19,20 +19,20 @@ from .base import AddressGroupServiceTransport from .grpc import AddressGroupServiceGrpcTransport from .grpc_asyncio import AddressGroupServiceGrpcAsyncIOTransport -from .rest import AddressGroupServiceRestTransport -from .rest import AddressGroupServiceRestInterceptor - +from .rest import AddressGroupServiceRestInterceptor, AddressGroupServiceRestTransport # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AddressGroupServiceTransport]] -_transport_registry['grpc'] = AddressGroupServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AddressGroupServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AddressGroupServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[AddressGroupServiceTransport]] +_transport_registry["grpc"] = AddressGroupServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AddressGroupServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AddressGroupServiceRestTransport __all__ = ( - 'AddressGroupServiceTransport', - 'AddressGroupServiceGrpcTransport', - 'AddressGroupServiceGrpcAsyncIOTransport', - 'AddressGroupServiceRestTransport', - 'AddressGroupServiceRestInterceptor', + "AddressGroupServiceTransport", + "AddressGroupServiceGrpcTransport", + "AddressGroupServiceGrpcAsyncIOTransport", + "AddressGroupServiceRestTransport", + "AddressGroupServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/base.py similarity index 69% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/base.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/base.py index 3a965a8989b9..fe76207bf3cf 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/base.py @@ -16,26 +16,26 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.network_security_v1 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1 import gapic_version as package_version from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.network_security_v1.types import address_group -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -44,24 +44,23 @@ class AddressGroupServiceTransport(abc.ABC): """Abstract transport class for AddressGroupService.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'networksecurity.googleapis.com' + DEFAULT_HOST: str = "networksecurity.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -97,30 +96,38 @@ def __init__( # 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") + 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 - ) + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host @property @@ -220,14 +227,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -237,84 +244,90 @@ def operations_client(self): raise NotImplementedError() @property - def list_address_groups(self) -> Callable[ - [address_group.ListAddressGroupsRequest], - Union[ - address_group.ListAddressGroupsResponse, - Awaitable[address_group.ListAddressGroupsResponse] - ]]: + def list_address_groups( + self, + ) -> Callable[ + [address_group.ListAddressGroupsRequest], + Union[ + address_group.ListAddressGroupsResponse, + Awaitable[address_group.ListAddressGroupsResponse], + ], + ]: raise NotImplementedError() @property - def get_address_group(self) -> Callable[ - [address_group.GetAddressGroupRequest], - Union[ - address_group.AddressGroup, - Awaitable[address_group.AddressGroup] - ]]: + def get_address_group( + self, + ) -> Callable[ + [address_group.GetAddressGroupRequest], + Union[address_group.AddressGroup, Awaitable[address_group.AddressGroup]], + ]: raise NotImplementedError() @property - def create_address_group(self) -> Callable[ - [gcn_address_group.CreateAddressGroupRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_address_group( + self, + ) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_address_group(self) -> Callable[ - [gcn_address_group.UpdateAddressGroupRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_address_group( + self, + ) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def add_address_group_items(self) -> Callable[ - [gcn_address_group.AddAddressGroupItemsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def add_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def remove_address_group_items(self) -> Callable[ - [gcn_address_group.RemoveAddressGroupItemsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def remove_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def clone_address_group_items(self) -> Callable[ - [gcn_address_group.CloneAddressGroupItemsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def clone_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_address_group(self) -> Callable[ - [address_group.DeleteAddressGroupRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_address_group( + self, + ) -> Callable[ + [address_group.DeleteAddressGroupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def list_address_group_references(self) -> Callable[ - [gcn_address_group.ListAddressGroupReferencesRequest], - Union[ - gcn_address_group.ListAddressGroupReferencesResponse, - Awaitable[gcn_address_group.ListAddressGroupReferencesResponse] - ]]: + def list_address_group_references( + self, + ) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + Union[ + gcn_address_group.ListAddressGroupReferencesResponse, + Awaitable[gcn_address_group.ListAddressGroupReferencesResponse], + ], + ]: raise NotImplementedError() @property @@ -322,7 +335,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -338,19 +354,13 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property def delete_operation( self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: raise NotImplementedError() @property @@ -384,7 +394,8 @@ def test_iam_permissions( raise NotImplementedError() @property - def get_location(self, + def get_location( + self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -392,10 +403,14 @@ def get_location(self, raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -404,6 +419,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'AddressGroupServiceTransport', -) +__all__ = ("AddressGroupServiceTransport",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py similarity index 82% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py index 2ed4732e7b02..ea072b89ea29 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/grpc.py @@ -16,31 +16,30 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.types import address_group from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import AddressGroupServiceTransport, DEFAULT_CLIENT_INFO +from google.cloud.network_security_v1.types import address_group + +from .base import DEFAULT_CLIENT_INFO, AddressGroupServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -50,7 +49,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -71,7 +72,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -82,7 +83,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -97,7 +102,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": client_call_details.method, "response": grpc_response, @@ -122,23 +127,26 @@ class AddressGroupServiceGrpcTransport(AddressGroupServiceTransport): 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -261,19 +269,23 @@ def __init__(self, *, ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -308,13 +320,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -334,9 +345,12 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_address_groups(self) -> Callable[ - [address_group.ListAddressGroupsRequest], - address_group.ListAddressGroupsResponse]: + def list_address_groups( + self, + ) -> Callable[ + [address_group.ListAddressGroupsRequest], + address_group.ListAddressGroupsResponse, + ]: r"""Return a callable for the list address groups method over gRPC. Lists address groups in a given project and location. @@ -351,18 +365,18 @@ def list_address_groups(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_address_groups' not in self._stubs: - self._stubs['list_address_groups'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroups', + if "list_address_groups" not in self._stubs: + self._stubs["list_address_groups"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroups", request_serializer=address_group.ListAddressGroupsRequest.serialize, response_deserializer=address_group.ListAddressGroupsResponse.deserialize, ) - return self._stubs['list_address_groups'] + return self._stubs["list_address_groups"] @property - def get_address_group(self) -> Callable[ - [address_group.GetAddressGroupRequest], - address_group.AddressGroup]: + def get_address_group( + self, + ) -> Callable[[address_group.GetAddressGroupRequest], address_group.AddressGroup]: r"""Return a callable for the get address group method over gRPC. Gets details of a single address group. @@ -377,18 +391,20 @@ def get_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_address_group' not in self._stubs: - self._stubs['get_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/GetAddressGroup', + if "get_address_group" not in self._stubs: + self._stubs["get_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/GetAddressGroup", request_serializer=address_group.GetAddressGroupRequest.serialize, response_deserializer=address_group.AddressGroup.deserialize, ) - return self._stubs['get_address_group'] + return self._stubs["get_address_group"] @property - def create_address_group(self) -> Callable[ - [gcn_address_group.CreateAddressGroupRequest], - operations_pb2.Operation]: + def create_address_group( + self, + ) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], operations_pb2.Operation + ]: r"""Return a callable for the create address group method over gRPC. Creates a new address group in a given project and @@ -404,18 +420,20 @@ def create_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_address_group' not in self._stubs: - self._stubs['create_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/CreateAddressGroup', + if "create_address_group" not in self._stubs: + self._stubs["create_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/CreateAddressGroup", request_serializer=gcn_address_group.CreateAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_address_group'] + return self._stubs["create_address_group"] @property - def update_address_group(self) -> Callable[ - [gcn_address_group.UpdateAddressGroupRequest], - operations_pb2.Operation]: + def update_address_group( + self, + ) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], operations_pb2.Operation + ]: r"""Return a callable for the update address group method over gRPC. Updates the parameters of a single address group. @@ -430,18 +448,20 @@ def update_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_address_group' not in self._stubs: - self._stubs['update_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/UpdateAddressGroup', + if "update_address_group" not in self._stubs: + self._stubs["update_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/UpdateAddressGroup", request_serializer=gcn_address_group.UpdateAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_address_group'] + return self._stubs["update_address_group"] @property - def add_address_group_items(self) -> Callable[ - [gcn_address_group.AddAddressGroupItemsRequest], - operations_pb2.Operation]: + def add_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], operations_pb2.Operation + ]: r"""Return a callable for the add address group items method over gRPC. Adds items to an address group. @@ -456,18 +476,20 @@ def add_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'add_address_group_items' not in self._stubs: - self._stubs['add_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/AddAddressGroupItems', + if "add_address_group_items" not in self._stubs: + self._stubs["add_address_group_items"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/AddAddressGroupItems", request_serializer=gcn_address_group.AddAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['add_address_group_items'] + return self._stubs["add_address_group_items"] @property - def remove_address_group_items(self) -> Callable[ - [gcn_address_group.RemoveAddressGroupItemsRequest], - operations_pb2.Operation]: + def remove_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], operations_pb2.Operation + ]: r"""Return a callable for the remove address group items method over gRPC. Removes items from an address group. @@ -482,18 +504,22 @@ def remove_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'remove_address_group_items' not in self._stubs: - self._stubs['remove_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/RemoveAddressGroupItems', + if "remove_address_group_items" not in self._stubs: + self._stubs[ + "remove_address_group_items" + ] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/RemoveAddressGroupItems", request_serializer=gcn_address_group.RemoveAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['remove_address_group_items'] + return self._stubs["remove_address_group_items"] @property - def clone_address_group_items(self) -> Callable[ - [gcn_address_group.CloneAddressGroupItemsRequest], - operations_pb2.Operation]: + def clone_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], operations_pb2.Operation + ]: r"""Return a callable for the clone address group items method over gRPC. Clones items from one address group to another. @@ -508,18 +534,18 @@ def clone_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'clone_address_group_items' not in self._stubs: - self._stubs['clone_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/CloneAddressGroupItems', + if "clone_address_group_items" not in self._stubs: + self._stubs["clone_address_group_items"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/CloneAddressGroupItems", request_serializer=gcn_address_group.CloneAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['clone_address_group_items'] + return self._stubs["clone_address_group_items"] @property - def delete_address_group(self) -> Callable[ - [address_group.DeleteAddressGroupRequest], - operations_pb2.Operation]: + def delete_address_group( + self, + ) -> Callable[[address_group.DeleteAddressGroupRequest], operations_pb2.Operation]: r"""Return a callable for the delete address group method over gRPC. Deletes a single address group. @@ -534,18 +560,21 @@ def delete_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_address_group' not in self._stubs: - self._stubs['delete_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/DeleteAddressGroup', + if "delete_address_group" not in self._stubs: + self._stubs["delete_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/DeleteAddressGroup", request_serializer=address_group.DeleteAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_address_group'] + return self._stubs["delete_address_group"] @property - def list_address_group_references(self) -> Callable[ - [gcn_address_group.ListAddressGroupReferencesRequest], - gcn_address_group.ListAddressGroupReferencesResponse]: + def list_address_group_references( + self, + ) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + gcn_address_group.ListAddressGroupReferencesResponse, + ]: r"""Return a callable for the list address group references method over gRPC. Lists references of an address group. @@ -560,13 +589,15 @@ def list_address_group_references(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_address_group_references' not in self._stubs: - self._stubs['list_address_group_references'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroupReferences', + if "list_address_group_references" not in self._stubs: + self._stubs[ + "list_address_group_references" + ] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroupReferences", request_serializer=gcn_address_group.ListAddressGroupReferencesRequest.serialize, response_deserializer=gcn_address_group.ListAddressGroupReferencesResponse.deserialize, ) - return self._stubs['list_address_group_references'] + return self._stubs["list_address_group_references"] def close(self): self._logged_channel.close() @@ -575,8 +606,7 @@ def close(self): def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ + r"""Return a callable for the delete_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -593,8 +623,7 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -611,8 +640,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -628,9 +656,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -646,9 +675,10 @@ def list_operations( @property def list_locations( self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -665,8 +695,7 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -734,7 +763,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. Tests the specified permissions against the IAM access control @@ -763,6 +793,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'AddressGroupServiceGrpcTransport', -) +__all__ = ("AddressGroupServiceGrpcTransport",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py similarity index 83% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py index 623b087a6cd4..dbe9c986ce4a 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/grpc_asyncio.py @@ -15,36 +15,35 @@ # import inspect import json -import pickle import logging as std_logging -import warnings +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.types import address_group from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import AddressGroupServiceTransport, DEFAULT_CLIENT_INFO +from google.cloud.network_security_v1.types import address_group + +from .base import DEFAULT_CLIENT_INFO, AddressGroupServiceTransport from .grpc import AddressGroupServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -52,9 +51,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -75,7 +78,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -86,7 +89,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -101,7 +108,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -131,13 +138,15 @@ class AddressGroupServiceGrpcAsyncIOTransport(AddressGroupServiceTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: + def create_channel( + cls, + host: str = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -167,24 +176,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -309,7 +320,9 @@ def __init__(self, *, self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -340,9 +353,12 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def list_address_groups(self) -> Callable[ - [address_group.ListAddressGroupsRequest], - Awaitable[address_group.ListAddressGroupsResponse]]: + def list_address_groups( + self, + ) -> Callable[ + [address_group.ListAddressGroupsRequest], + Awaitable[address_group.ListAddressGroupsResponse], + ]: r"""Return a callable for the list address groups method over gRPC. Lists address groups in a given project and location. @@ -357,18 +373,20 @@ def list_address_groups(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_address_groups' not in self._stubs: - self._stubs['list_address_groups'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroups', + if "list_address_groups" not in self._stubs: + self._stubs["list_address_groups"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroups", request_serializer=address_group.ListAddressGroupsRequest.serialize, response_deserializer=address_group.ListAddressGroupsResponse.deserialize, ) - return self._stubs['list_address_groups'] + return self._stubs["list_address_groups"] @property - def get_address_group(self) -> Callable[ - [address_group.GetAddressGroupRequest], - Awaitable[address_group.AddressGroup]]: + def get_address_group( + self, + ) -> Callable[ + [address_group.GetAddressGroupRequest], Awaitable[address_group.AddressGroup] + ]: r"""Return a callable for the get address group method over gRPC. Gets details of a single address group. @@ -383,18 +401,21 @@ def get_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_address_group' not in self._stubs: - self._stubs['get_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/GetAddressGroup', + if "get_address_group" not in self._stubs: + self._stubs["get_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/GetAddressGroup", request_serializer=address_group.GetAddressGroupRequest.serialize, response_deserializer=address_group.AddressGroup.deserialize, ) - return self._stubs['get_address_group'] + return self._stubs["get_address_group"] @property - def create_address_group(self) -> Callable[ - [gcn_address_group.CreateAddressGroupRequest], - Awaitable[operations_pb2.Operation]]: + def create_address_group( + self, + ) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + Awaitable[operations_pb2.Operation], + ]: r"""Return a callable for the create address group method over gRPC. Creates a new address group in a given project and @@ -410,18 +431,21 @@ def create_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_address_group' not in self._stubs: - self._stubs['create_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/CreateAddressGroup', + if "create_address_group" not in self._stubs: + self._stubs["create_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/CreateAddressGroup", request_serializer=gcn_address_group.CreateAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_address_group'] + return self._stubs["create_address_group"] @property - def update_address_group(self) -> Callable[ - [gcn_address_group.UpdateAddressGroupRequest], - Awaitable[operations_pb2.Operation]]: + def update_address_group( + self, + ) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + Awaitable[operations_pb2.Operation], + ]: r"""Return a callable for the update address group method over gRPC. Updates the parameters of a single address group. @@ -436,18 +460,21 @@ def update_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_address_group' not in self._stubs: - self._stubs['update_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/UpdateAddressGroup', + if "update_address_group" not in self._stubs: + self._stubs["update_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/UpdateAddressGroup", request_serializer=gcn_address_group.UpdateAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_address_group'] + return self._stubs["update_address_group"] @property - def add_address_group_items(self) -> Callable[ - [gcn_address_group.AddAddressGroupItemsRequest], - Awaitable[operations_pb2.Operation]]: + def add_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation], + ]: r"""Return a callable for the add address group items method over gRPC. Adds items to an address group. @@ -462,18 +489,21 @@ def add_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'add_address_group_items' not in self._stubs: - self._stubs['add_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/AddAddressGroupItems', + if "add_address_group_items" not in self._stubs: + self._stubs["add_address_group_items"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/AddAddressGroupItems", request_serializer=gcn_address_group.AddAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['add_address_group_items'] + return self._stubs["add_address_group_items"] @property - def remove_address_group_items(self) -> Callable[ - [gcn_address_group.RemoveAddressGroupItemsRequest], - Awaitable[operations_pb2.Operation]]: + def remove_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation], + ]: r"""Return a callable for the remove address group items method over gRPC. Removes items from an address group. @@ -488,18 +518,23 @@ def remove_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'remove_address_group_items' not in self._stubs: - self._stubs['remove_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/RemoveAddressGroupItems', + if "remove_address_group_items" not in self._stubs: + self._stubs[ + "remove_address_group_items" + ] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/RemoveAddressGroupItems", request_serializer=gcn_address_group.RemoveAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['remove_address_group_items'] + return self._stubs["remove_address_group_items"] @property - def clone_address_group_items(self) -> Callable[ - [gcn_address_group.CloneAddressGroupItemsRequest], - Awaitable[operations_pb2.Operation]]: + def clone_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation], + ]: r"""Return a callable for the clone address group items method over gRPC. Clones items from one address group to another. @@ -514,18 +549,20 @@ def clone_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'clone_address_group_items' not in self._stubs: - self._stubs['clone_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/CloneAddressGroupItems', + if "clone_address_group_items" not in self._stubs: + self._stubs["clone_address_group_items"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/CloneAddressGroupItems", request_serializer=gcn_address_group.CloneAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['clone_address_group_items'] + return self._stubs["clone_address_group_items"] @property - def delete_address_group(self) -> Callable[ - [address_group.DeleteAddressGroupRequest], - Awaitable[operations_pb2.Operation]]: + def delete_address_group( + self, + ) -> Callable[ + [address_group.DeleteAddressGroupRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete address group method over gRPC. Deletes a single address group. @@ -540,18 +577,21 @@ def delete_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_address_group' not in self._stubs: - self._stubs['delete_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/DeleteAddressGroup', + if "delete_address_group" not in self._stubs: + self._stubs["delete_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/DeleteAddressGroup", request_serializer=address_group.DeleteAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_address_group'] + return self._stubs["delete_address_group"] @property - def list_address_group_references(self) -> Callable[ - [gcn_address_group.ListAddressGroupReferencesRequest], - Awaitable[gcn_address_group.ListAddressGroupReferencesResponse]]: + def list_address_group_references( + self, + ) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + Awaitable[gcn_address_group.ListAddressGroupReferencesResponse], + ]: r"""Return a callable for the list address group references method over gRPC. Lists references of an address group. @@ -566,16 +606,18 @@ def list_address_group_references(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_address_group_references' not in self._stubs: - self._stubs['list_address_group_references'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroupReferences', + if "list_address_group_references" not in self._stubs: + self._stubs[ + "list_address_group_references" + ] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.AddressGroupService/ListAddressGroupReferences", request_serializer=gcn_address_group.ListAddressGroupReferencesRequest.serialize, response_deserializer=gcn_address_group.ListAddressGroupReferencesResponse.deserialize, ) - return self._stubs['list_address_group_references'] + return self._stubs["list_address_group_references"] def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.list_address_groups: self._wrap_method( self.list_address_groups, @@ -685,8 +727,7 @@ def kind(self) -> str: def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ + r"""Return a callable for the delete_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -703,8 +744,7 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -721,8 +761,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -738,9 +777,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -756,9 +796,10 @@ def list_operations( @property def list_locations( self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -775,8 +816,7 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -844,7 +884,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. Tests the specified permissions against the IAM access control @@ -869,6 +910,4 @@ def test_iam_permissions( return self._stubs["test_iam_permissions"] -__all__ = ( - 'AddressGroupServiceGrpcAsyncIOTransport', -) +__all__ = ("AddressGroupServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/rest.py similarity index 65% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/rest.py index 1249881d1198..ba7df4811af8 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/rest.py @@ -13,37 +13,30 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging +import dataclasses import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 -import google.protobuf - -from google.protobuf import json_format -from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf +from google.protobuf import json_format from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -from google.cloud.network_security_v1.types import address_group from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.longrunning import operations_pb2 # type: ignore - +from google.cloud.network_security_v1.types import address_group -from .rest_base import _BaseAddressGroupServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAddressGroupServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -52,6 +45,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -160,7 +154,15 @@ def post_update_address_group(self, response): """ - def pre_add_address_group_items(self, request: gcn_address_group.AddAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.AddAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_add_address_group_items( + self, + request: gcn_address_group.AddAddressGroupItemsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.AddAddressGroupItemsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for add_address_group_items Override in a subclass to manipulate the request or metadata @@ -168,7 +170,9 @@ def pre_add_address_group_items(self, request: gcn_address_group.AddAddressGroup """ return request, metadata - def post_add_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_add_address_group_items( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for add_address_group_items DEPRECATED. Please use the `post_add_address_group_items_with_metadata` @@ -181,7 +185,11 @@ def post_add_address_group_items(self, response: operations_pb2.Operation) -> op """ return response - def post_add_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_add_address_group_items_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for add_address_group_items Override in a subclass to read or manipulate the response or metadata after it @@ -196,7 +204,14 @@ def post_add_address_group_items_with_metadata(self, response: operations_pb2.Op """ return response, metadata - def pre_clone_address_group_items(self, request: gcn_address_group.CloneAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.CloneAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_clone_address_group_items( + self, + request: gcn_address_group.CloneAddressGroupItemsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.CloneAddressGroupItemsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for clone_address_group_items Override in a subclass to manipulate the request or metadata @@ -204,7 +219,9 @@ def pre_clone_address_group_items(self, request: gcn_address_group.CloneAddressG """ return request, metadata - def post_clone_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_clone_address_group_items( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for clone_address_group_items DEPRECATED. Please use the `post_clone_address_group_items_with_metadata` @@ -217,7 +234,11 @@ def post_clone_address_group_items(self, response: operations_pb2.Operation) -> """ return response - def post_clone_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_clone_address_group_items_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for clone_address_group_items Override in a subclass to read or manipulate the response or metadata after it @@ -232,7 +253,14 @@ def post_clone_address_group_items_with_metadata(self, response: operations_pb2. """ return response, metadata - def pre_create_address_group(self, request: gcn_address_group.CreateAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.CreateAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_address_group( + self, + request: gcn_address_group.CreateAddressGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.CreateAddressGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_address_group Override in a subclass to manipulate the request or metadata @@ -240,7 +268,9 @@ def pre_create_address_group(self, request: gcn_address_group.CreateAddressGroup """ return request, metadata - def post_create_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_address_group( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_address_group DEPRECATED. Please use the `post_create_address_group_with_metadata` @@ -253,7 +283,11 @@ def post_create_address_group(self, response: operations_pb2.Operation) -> opera """ return response - def post_create_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_address_group_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_address_group Override in a subclass to read or manipulate the response or metadata after it @@ -268,7 +302,13 @@ def post_create_address_group_with_metadata(self, response: operations_pb2.Opera """ return response, metadata - def pre_delete_address_group(self, request: address_group.DeleteAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.DeleteAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_address_group( + self, + request: address_group.DeleteAddressGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + address_group.DeleteAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_address_group Override in a subclass to manipulate the request or metadata @@ -276,7 +316,9 @@ def pre_delete_address_group(self, request: address_group.DeleteAddressGroupRequ """ return request, metadata - def post_delete_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_address_group( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_address_group DEPRECATED. Please use the `post_delete_address_group_with_metadata` @@ -289,7 +331,11 @@ def post_delete_address_group(self, response: operations_pb2.Operation) -> opera """ return response - def post_delete_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_address_group_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_address_group Override in a subclass to read or manipulate the response or metadata after it @@ -304,7 +350,13 @@ def post_delete_address_group_with_metadata(self, response: operations_pb2.Opera """ return response, metadata - def pre_get_address_group(self, request: address_group.GetAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.GetAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_address_group( + self, + request: address_group.GetAddressGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + address_group.GetAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_address_group Override in a subclass to manipulate the request or metadata @@ -312,7 +364,9 @@ def pre_get_address_group(self, request: address_group.GetAddressGroupRequest, m """ return request, metadata - def post_get_address_group(self, response: address_group.AddressGroup) -> address_group.AddressGroup: + def post_get_address_group( + self, response: address_group.AddressGroup + ) -> address_group.AddressGroup: """Post-rpc interceptor for get_address_group DEPRECATED. Please use the `post_get_address_group_with_metadata` @@ -325,7 +379,11 @@ def post_get_address_group(self, response: address_group.AddressGroup) -> addres """ return response - def post_get_address_group_with_metadata(self, response: address_group.AddressGroup, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.AddressGroup, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_address_group_with_metadata( + self, + response: address_group.AddressGroup, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[address_group.AddressGroup, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_address_group Override in a subclass to read or manipulate the response or metadata after it @@ -340,7 +398,14 @@ def post_get_address_group_with_metadata(self, response: address_group.AddressGr """ return response, metadata - def pre_list_address_group_references(self, request: gcn_address_group.ListAddressGroupReferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.ListAddressGroupReferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_address_group_references( + self, + request: gcn_address_group.ListAddressGroupReferencesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.ListAddressGroupReferencesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_address_group_references Override in a subclass to manipulate the request or metadata @@ -348,7 +413,9 @@ def pre_list_address_group_references(self, request: gcn_address_group.ListAddre """ return request, metadata - def post_list_address_group_references(self, response: gcn_address_group.ListAddressGroupReferencesResponse) -> gcn_address_group.ListAddressGroupReferencesResponse: + def post_list_address_group_references( + self, response: gcn_address_group.ListAddressGroupReferencesResponse + ) -> gcn_address_group.ListAddressGroupReferencesResponse: """Post-rpc interceptor for list_address_group_references DEPRECATED. Please use the `post_list_address_group_references_with_metadata` @@ -361,7 +428,14 @@ def post_list_address_group_references(self, response: gcn_address_group.ListAdd """ return response - def post_list_address_group_references_with_metadata(self, response: gcn_address_group.ListAddressGroupReferencesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.ListAddressGroupReferencesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_address_group_references_with_metadata( + self, + response: gcn_address_group.ListAddressGroupReferencesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.ListAddressGroupReferencesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_address_group_references Override in a subclass to read or manipulate the response or metadata after it @@ -376,7 +450,13 @@ def post_list_address_group_references_with_metadata(self, response: gcn_address """ return response, metadata - def pre_list_address_groups(self, request: address_group.ListAddressGroupsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.ListAddressGroupsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_address_groups( + self, + request: address_group.ListAddressGroupsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + address_group.ListAddressGroupsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_address_groups Override in a subclass to manipulate the request or metadata @@ -384,7 +464,9 @@ def pre_list_address_groups(self, request: address_group.ListAddressGroupsReques """ return request, metadata - def post_list_address_groups(self, response: address_group.ListAddressGroupsResponse) -> address_group.ListAddressGroupsResponse: + def post_list_address_groups( + self, response: address_group.ListAddressGroupsResponse + ) -> address_group.ListAddressGroupsResponse: """Post-rpc interceptor for list_address_groups DEPRECATED. Please use the `post_list_address_groups_with_metadata` @@ -397,7 +479,13 @@ def post_list_address_groups(self, response: address_group.ListAddressGroupsResp """ return response - def post_list_address_groups_with_metadata(self, response: address_group.ListAddressGroupsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.ListAddressGroupsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_address_groups_with_metadata( + self, + response: address_group.ListAddressGroupsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + address_group.ListAddressGroupsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_address_groups Override in a subclass to read or manipulate the response or metadata after it @@ -412,7 +500,14 @@ def post_list_address_groups_with_metadata(self, response: address_group.ListAdd """ return response, metadata - def pre_remove_address_group_items(self, request: gcn_address_group.RemoveAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.RemoveAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_remove_address_group_items( + self, + request: gcn_address_group.RemoveAddressGroupItemsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.RemoveAddressGroupItemsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for remove_address_group_items Override in a subclass to manipulate the request or metadata @@ -420,7 +515,9 @@ def pre_remove_address_group_items(self, request: gcn_address_group.RemoveAddres """ return request, metadata - def post_remove_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_remove_address_group_items( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for remove_address_group_items DEPRECATED. Please use the `post_remove_address_group_items_with_metadata` @@ -433,7 +530,11 @@ def post_remove_address_group_items(self, response: operations_pb2.Operation) -> """ return response - def post_remove_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_remove_address_group_items_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for remove_address_group_items Override in a subclass to read or manipulate the response or metadata after it @@ -448,7 +549,14 @@ def post_remove_address_group_items_with_metadata(self, response: operations_pb2 """ return response, metadata - def pre_update_address_group(self, request: gcn_address_group.UpdateAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.UpdateAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_address_group( + self, + request: gcn_address_group.UpdateAddressGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.UpdateAddressGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_address_group Override in a subclass to manipulate the request or metadata @@ -456,7 +564,9 @@ def pre_update_address_group(self, request: gcn_address_group.UpdateAddressGroup """ return request, metadata - def post_update_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_update_address_group( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_address_group DEPRECATED. Please use the `post_update_address_group_with_metadata` @@ -469,7 +579,11 @@ def post_update_address_group(self, response: operations_pb2.Operation) -> opera """ return response - def post_update_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_address_group_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_address_group Override in a subclass to read or manipulate the response or metadata after it @@ -485,8 +599,12 @@ def post_update_address_group_with_metadata(self, response: operations_pb2.Opera return response, metadata def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -506,8 +624,12 @@ def post_get_location( return response def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -527,8 +649,12 @@ def post_list_locations( return response def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_iam_policy Override in a subclass to manipulate the request or metadata @@ -536,9 +662,7 @@ def pre_get_iam_policy( """ return request, metadata - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for get_iam_policy Override in a subclass to manipulate the response @@ -548,8 +672,12 @@ def post_get_iam_policy( return response def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for set_iam_policy Override in a subclass to manipulate the request or metadata @@ -557,9 +685,7 @@ def pre_set_iam_policy( """ return request, metadata - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for set_iam_policy Override in a subclass to manipulate the response @@ -569,8 +695,13 @@ def post_set_iam_policy( return response def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for test_iam_permissions Override in a subclass to manipulate the request or metadata @@ -590,8 +721,12 @@ def post_test_iam_permissions( return response def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -599,9 +734,7 @@ def pre_cancel_operation( """ return request, metadata - def post_cancel_operation( - self, response: None - ) -> None: + def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -611,8 +744,12 @@ def post_cancel_operation( return response def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -620,9 +757,7 @@ def pre_delete_operation( """ return request, metadata - def post_delete_operation( - self, response: None - ) -> None: + def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -632,8 +767,12 @@ def post_delete_operation( return response def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -653,8 +792,12 @@ def post_get_operation( return response def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -696,20 +839,21 @@ class AddressGroupServiceRestTransport(_BaseAddressGroupServiceRestTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[AddressGroupServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AddressGroupServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -752,10 +896,11 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) @@ -772,64 +917,70 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ + "google.longrunning.Operations.CancelOperation": [ { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", }, { - 'method': 'post', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', - 'body': '*', + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}:cancel", + "body": "*", }, ], - 'google.longrunning.Operations.DeleteOperation': [ + "google.longrunning.Operations.DeleteOperation": [ { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, { - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.ListOperations': [ + "google.longrunning.Operations.ListOperations": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", }, { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}/operations', + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}/operations", }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client - class _AddAddressGroupItems(_BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems, AddressGroupServiceRestStub): + class _AddAddressGroupItems( + _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.AddAddressGroupItems") @@ -841,27 +992,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: gcn_address_group.AddAddressGroupItemsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: gcn_address_group.AddAddressGroupItemsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the add address group items method over HTTP. Args: @@ -884,32 +1037,46 @@ def __call__(self, """ - http_options = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_http_options() + ) - request, metadata = self._interceptor.pre_add_address_group_items(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_add_address_group_items( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_transcoded_request( + http_options, request + ) - body = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_request_body_json(transcoded_request) + body = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.AddAddressGroupItems", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "AddAddressGroupItems", "httpRequest": http_request, @@ -918,7 +1085,17 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._AddAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + AddressGroupServiceRestTransport._AddAddressGroupItems._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -931,20 +1108,24 @@ def __call__(self, resp = self._interceptor.post_add_address_group_items(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_add_address_group_items_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_add_address_group_items_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.add_address_group_items", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "AddAddressGroupItems", "metadata": http_response["headers"], @@ -953,7 +1134,10 @@ def __call__(self, ) return resp - class _CloneAddressGroupItems(_BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems, AddressGroupServiceRestStub): + class _CloneAddressGroupItems( + _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.CloneAddressGroupItems") @@ -965,27 +1149,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: gcn_address_group.CloneAddressGroupItemsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: gcn_address_group.CloneAddressGroupItemsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the clone address group items method over HTTP. Args: @@ -1008,32 +1194,46 @@ def __call__(self, """ - http_options = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_http_options() + ) - request, metadata = self._interceptor.pre_clone_address_group_items(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_clone_address_group_items( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_transcoded_request( + http_options, request + ) - body = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_request_body_json(transcoded_request) + body = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.CloneAddressGroupItems", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "CloneAddressGroupItems", "httpRequest": http_request, @@ -1042,7 +1242,17 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._CloneAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + AddressGroupServiceRestTransport._CloneAddressGroupItems._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1055,20 +1265,24 @@ def __call__(self, resp = self._interceptor.post_clone_address_group_items(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_clone_address_group_items_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_clone_address_group_items_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.clone_address_group_items", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "CloneAddressGroupItems", "metadata": http_response["headers"], @@ -1077,7 +1291,10 @@ def __call__(self, ) return resp - class _CreateAddressGroup(_BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup, AddressGroupServiceRestStub): + class _CreateAddressGroup( + _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.CreateAddressGroup") @@ -1089,27 +1306,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: gcn_address_group.CreateAddressGroupRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: gcn_address_group.CreateAddressGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create address group method over HTTP. Args: @@ -1132,32 +1351,46 @@ def __call__(self, """ - http_options = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_http_options() + ) - request, metadata = self._interceptor.pre_create_address_group(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_address_group( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_transcoded_request( + http_options, request + ) - body = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_request_body_json(transcoded_request) + body = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.CreateAddressGroup", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "CreateAddressGroup", "httpRequest": http_request, @@ -1166,7 +1399,17 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._CreateAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + AddressGroupServiceRestTransport._CreateAddressGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1179,20 +1422,24 @@ def __call__(self, resp = self._interceptor.post_create_address_group(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_address_group_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_address_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.create_address_group", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "CreateAddressGroup", "metadata": http_response["headers"], @@ -1201,7 +1448,10 @@ def __call__(self, ) return resp - class _DeleteAddressGroup(_BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup, AddressGroupServiceRestStub): + class _DeleteAddressGroup( + _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.DeleteAddressGroup") @@ -1213,26 +1463,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: address_group.DeleteAddressGroupRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: address_group.DeleteAddressGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete address group method over HTTP. Args: @@ -1255,30 +1507,42 @@ def __call__(self, """ - http_options = _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_address_group(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_address_group( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.DeleteAddressGroup", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "DeleteAddressGroup", "httpRequest": http_request, @@ -1287,7 +1551,16 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._DeleteAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + AddressGroupServiceRestTransport._DeleteAddressGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1300,20 +1573,24 @@ def __call__(self, resp = self._interceptor.post_delete_address_group(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_address_group_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_address_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.delete_address_group", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "DeleteAddressGroup", "metadata": http_response["headers"], @@ -1322,7 +1599,10 @@ def __call__(self, ) return resp - class _GetAddressGroup(_BaseAddressGroupServiceRestTransport._BaseGetAddressGroup, AddressGroupServiceRestStub): + class _GetAddressGroup( + _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.GetAddressGroup") @@ -1334,26 +1614,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: address_group.GetAddressGroupRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> address_group.AddressGroup: + def __call__( + self, + request: address_group.GetAddressGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.AddressGroup: r"""Call the get address group method over HTTP. Args: @@ -1376,30 +1658,42 @@ def __call__(self, """ - http_options = _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_http_options() + ) - request, metadata = self._interceptor.pre_get_address_group(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_address_group( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.GetAddressGroup", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "GetAddressGroup", "httpRequest": http_request, @@ -1408,7 +1702,14 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._GetAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AddressGroupServiceRestTransport._GetAddressGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1423,20 +1724,24 @@ def __call__(self, resp = self._interceptor.post_get_address_group(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_address_group_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_address_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = address_group.AddressGroup.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.get_address_group", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "GetAddressGroup", "metadata": http_response["headers"], @@ -1445,7 +1750,10 @@ def __call__(self, ) return resp - class _ListAddressGroupReferences(_BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences, AddressGroupServiceRestStub): + class _ListAddressGroupReferences( + _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.ListAddressGroupReferences") @@ -1457,72 +1765,86 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: gcn_address_group.ListAddressGroupReferencesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gcn_address_group.ListAddressGroupReferencesResponse: + def __call__( + self, + request: gcn_address_group.ListAddressGroupReferencesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcn_address_group.ListAddressGroupReferencesResponse: r"""Call the list address group - references method over HTTP. - - Args: - request (~.gcn_address_group.ListAddressGroupReferencesRequest): - The request object. Request used by the - ListAddressGroupReferences method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gcn_address_group.ListAddressGroupReferencesResponse: - Response of the - ListAddressGroupReferences method. + references method over HTTP. + + Args: + request (~.gcn_address_group.ListAddressGroupReferencesRequest): + The request object. Request used by the + ListAddressGroupReferences method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcn_address_group.ListAddressGroupReferencesResponse: + Response of the + ListAddressGroupReferences method. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_http_options() + ) - request, metadata = self._interceptor.pre_list_address_group_references(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_address_group_references( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.ListAddressGroupReferences", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "ListAddressGroupReferences", "httpRequest": http_request, @@ -1531,7 +1853,14 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._ListAddressGroupReferences._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AddressGroupServiceRestTransport._ListAddressGroupReferences._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1546,20 +1875,31 @@ def __call__(self, resp = self._interceptor.post_list_address_group_references(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_address_group_references_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_list_address_group_references_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = gcn_address_group.ListAddressGroupReferencesResponse.to_json(response) + response_payload = ( + gcn_address_group.ListAddressGroupReferencesResponse.to_json( + response + ) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.list_address_group_references", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "ListAddressGroupReferences", "metadata": http_response["headers"], @@ -1568,7 +1908,10 @@ def __call__(self, ) return resp - class _ListAddressGroups(_BaseAddressGroupServiceRestTransport._BaseListAddressGroups, AddressGroupServiceRestStub): + class _ListAddressGroups( + _BaseAddressGroupServiceRestTransport._BaseListAddressGroups, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.ListAddressGroups") @@ -1580,26 +1923,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: address_group.ListAddressGroupsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> address_group.ListAddressGroupsResponse: + def __call__( + self, + request: address_group.ListAddressGroupsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.ListAddressGroupsResponse: r"""Call the list address groups method over HTTP. Args: @@ -1621,30 +1966,42 @@ def __call__(self, """ - http_options = _BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_http_options() + ) - request, metadata = self._interceptor.pre_list_address_groups(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_address_groups( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.ListAddressGroups", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "ListAddressGroups", "httpRequest": http_request, @@ -1653,7 +2010,16 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._ListAddressGroups._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + AddressGroupServiceRestTransport._ListAddressGroups._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1668,20 +2034,26 @@ def __call__(self, resp = self._interceptor.post_list_address_groups(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_address_groups_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_address_groups_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = address_group.ListAddressGroupsResponse.to_json(response) + response_payload = address_group.ListAddressGroupsResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.list_address_groups", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "ListAddressGroups", "metadata": http_response["headers"], @@ -1690,7 +2062,10 @@ def __call__(self, ) return resp - class _RemoveAddressGroupItems(_BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems, AddressGroupServiceRestStub): + class _RemoveAddressGroupItems( + _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.RemoveAddressGroupItems") @@ -1702,76 +2077,92 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: gcn_address_group.RemoveAddressGroupItemsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: gcn_address_group.RemoveAddressGroupItemsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the remove address group - items method over HTTP. - - Args: - request (~.gcn_address_group.RemoveAddressGroupItemsRequest): - The request object. Request used by the - RemoveAddressGroupItems method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + items method over HTTP. + + Args: + request (~.gcn_address_group.RemoveAddressGroupItemsRequest): + The request object. Request used by the + RemoveAddressGroupItems method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_http_options() + ) - request, metadata = self._interceptor.pre_remove_address_group_items(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_remove_address_group_items( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_transcoded_request( + http_options, request + ) - body = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_request_body_json(transcoded_request) + body = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.RemoveAddressGroupItems", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "RemoveAddressGroupItems", "httpRequest": http_request, @@ -1780,7 +2171,17 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._RemoveAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + AddressGroupServiceRestTransport._RemoveAddressGroupItems._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1793,20 +2194,24 @@ def __call__(self, resp = self._interceptor.post_remove_address_group_items(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_remove_address_group_items_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_remove_address_group_items_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.remove_address_group_items", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "RemoveAddressGroupItems", "metadata": http_response["headers"], @@ -1815,7 +2220,10 @@ def __call__(self, ) return resp - class _UpdateAddressGroup(_BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup, AddressGroupServiceRestStub): + class _UpdateAddressGroup( + _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.UpdateAddressGroup") @@ -1827,27 +2235,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: gcn_address_group.UpdateAddressGroupRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: gcn_address_group.UpdateAddressGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update address group method over HTTP. Args: @@ -1870,32 +2280,46 @@ def __call__(self, """ - http_options = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_http_options() + ) - request, metadata = self._interceptor.pre_update_address_group(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_address_group( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_transcoded_request( + http_options, request + ) - body = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_request_body_json(transcoded_request) + body = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.UpdateAddressGroup", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "UpdateAddressGroup", "httpRequest": http_request, @@ -1904,7 +2328,17 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._UpdateAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + AddressGroupServiceRestTransport._UpdateAddressGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1917,20 +2351,24 @@ def __call__(self, resp = self._interceptor.post_update_address_group(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_address_group_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_address_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceClient.update_address_group", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "UpdateAddressGroup", "metadata": http_response["headers"], @@ -1940,82 +2378,101 @@ def __call__(self, return resp @property - def add_address_group_items(self) -> Callable[ - [gcn_address_group.AddAddressGroupItemsRequest], - operations_pb2.Operation]: + def add_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AddAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + return self._AddAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore @property - def clone_address_group_items(self) -> Callable[ - [gcn_address_group.CloneAddressGroupItemsRequest], - operations_pb2.Operation]: + def clone_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CloneAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + return self._CloneAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore @property - def create_address_group(self) -> Callable[ - [gcn_address_group.CreateAddressGroupRequest], - operations_pb2.Operation]: + def create_address_group( + self, + ) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateAddressGroup(self._session, self._host, self._interceptor) # type: ignore + return self._CreateAddressGroup(self._session, self._host, self._interceptor) # type: ignore @property - def delete_address_group(self) -> Callable[ - [address_group.DeleteAddressGroupRequest], - operations_pb2.Operation]: + def delete_address_group( + self, + ) -> Callable[[address_group.DeleteAddressGroupRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteAddressGroup(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteAddressGroup(self._session, self._host, self._interceptor) # type: ignore @property - def get_address_group(self) -> Callable[ - [address_group.GetAddressGroupRequest], - address_group.AddressGroup]: + def get_address_group( + self, + ) -> Callable[[address_group.GetAddressGroupRequest], address_group.AddressGroup]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetAddressGroup(self._session, self._host, self._interceptor) # type: ignore + return self._GetAddressGroup(self._session, self._host, self._interceptor) # type: ignore @property - def list_address_group_references(self) -> Callable[ - [gcn_address_group.ListAddressGroupReferencesRequest], - gcn_address_group.ListAddressGroupReferencesResponse]: + def list_address_group_references( + self, + ) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + gcn_address_group.ListAddressGroupReferencesResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListAddressGroupReferences(self._session, self._host, self._interceptor) # type: ignore + return self._ListAddressGroupReferences(self._session, self._host, self._interceptor) # type: ignore @property - def list_address_groups(self) -> Callable[ - [address_group.ListAddressGroupsRequest], - address_group.ListAddressGroupsResponse]: + def list_address_groups( + self, + ) -> Callable[ + [address_group.ListAddressGroupsRequest], + address_group.ListAddressGroupsResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListAddressGroups(self._session, self._host, self._interceptor) # type: ignore + return self._ListAddressGroups(self._session, self._host, self._interceptor) # type: ignore @property - def remove_address_group_items(self) -> Callable[ - [gcn_address_group.RemoveAddressGroupItemsRequest], - operations_pb2.Operation]: + def remove_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._RemoveAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + return self._RemoveAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore @property - def update_address_group(self) -> Callable[ - [gcn_address_group.UpdateAddressGroupRequest], - operations_pb2.Operation]: + def update_address_group( + self, + ) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateAddressGroup(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateAddressGroup(self._session, self._host, self._interceptor) # type: ignore @property def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(_BaseAddressGroupServiceRestTransport._BaseGetLocation, AddressGroupServiceRestStub): + class _GetLocation( + _BaseAddressGroupServiceRestTransport._BaseGetLocation, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.GetLocation") @@ -2027,27 +2484,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: r"""Call the get location method over HTTP. Args: @@ -2065,30 +2523,40 @@ def __call__(self, locations_pb2.Location: Response from GetLocation method. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseGetLocation._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "GetLocation", "httpRequest": http_request, @@ -2097,7 +2565,14 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AddressGroupServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2108,19 +2583,21 @@ def __call__(self, resp = locations_pb2.Location() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "GetLocation", "httpResponse": http_response, @@ -2131,9 +2608,12 @@ def __call__(self, @property def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(_BaseAddressGroupServiceRestTransport._BaseListLocations, AddressGroupServiceRestStub): + class _ListLocations( + _BaseAddressGroupServiceRestTransport._BaseListLocations, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.ListLocations") @@ -2145,27 +2625,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: r"""Call the list locations method over HTTP. Args: @@ -2183,30 +2664,40 @@ def __call__(self, locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseListLocations._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "ListLocations", "httpRequest": http_request, @@ -2215,7 +2706,14 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AddressGroupServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2226,19 +2724,21 @@ def __call__(self, resp = locations_pb2.ListLocationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "ListLocations", "httpResponse": http_response, @@ -2249,9 +2749,12 @@ def __call__(self, @property def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - class _GetIamPolicy(_BaseAddressGroupServiceRestTransport._BaseGetIamPolicy, AddressGroupServiceRestStub): + class _GetIamPolicy( + _BaseAddressGroupServiceRestTransport._BaseGetIamPolicy, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.GetIamPolicy") @@ -2263,27 +2766,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: r"""Call the get iam policy method over HTTP. Args: @@ -2301,30 +2805,40 @@ def __call__(self, policy_pb2.Policy: Response from GetIamPolicy method. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseGetIamPolicy._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseGetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.GetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "GetIamPolicy", "httpRequest": http_request, @@ -2333,7 +2847,14 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AddressGroupServiceRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2344,19 +2865,21 @@ def __call__(self, resp = policy_pb2.Policy() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.GetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "GetIamPolicy", "httpResponse": http_response, @@ -2367,9 +2890,12 @@ def __call__(self, @property def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - class _SetIamPolicy(_BaseAddressGroupServiceRestTransport._BaseSetIamPolicy, AddressGroupServiceRestStub): + class _SetIamPolicy( + _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.SetIamPolicy") @@ -2381,28 +2907,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: r"""Call the set iam policy method over HTTP. Args: @@ -2420,32 +2947,44 @@ def __call__(self, policy_pb2.Policy: Response from SetIamPolicy method. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) - body = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + body = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.SetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "SetIamPolicy", "httpRequest": http_request, @@ -2454,7 +2993,15 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AddressGroupServiceRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2465,19 +3012,21 @@ def __call__(self, resp = policy_pb2.Policy() resp = json_format.Parse(content, resp) resp = self._interceptor.post_set_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.SetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "SetIamPolicy", "httpResponse": http_response, @@ -2488,9 +3037,12 @@ def __call__(self, @property def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - class _TestIamPermissions(_BaseAddressGroupServiceRestTransport._BaseTestIamPermissions, AddressGroupServiceRestStub): + class _TestIamPermissions( + _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.TestIamPermissions") @@ -2502,28 +3054,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Call the test iam permissions method over HTTP. Args: @@ -2541,32 +3094,46 @@ def __call__(self, iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_http_options() + ) - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + body = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.TestIamPermissions", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "TestIamPermissions", "httpRequest": http_request, @@ -2575,7 +3142,17 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + AddressGroupServiceRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2586,19 +3163,21 @@ def __call__(self, resp = iam_policy_pb2.TestIamPermissionsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_test_iam_permissions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.TestIamPermissions", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "TestIamPermissions", "httpResponse": http_response, @@ -2609,9 +3188,12 @@ def __call__(self, @property def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(_BaseAddressGroupServiceRestTransport._BaseCancelOperation, AddressGroupServiceRestStub): + class _CancelOperation( + _BaseAddressGroupServiceRestTransport._BaseCancelOperation, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.CancelOperation") @@ -2623,28 +3205,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the cancel operation method over HTTP. Args: @@ -2659,32 +3242,46 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) - body = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + body = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.CancelOperation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "CancelOperation", "httpRequest": http_request, @@ -2693,7 +3290,15 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AddressGroupServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2704,9 +3309,12 @@ def __call__(self, @property def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(_BaseAddressGroupServiceRestTransport._BaseDeleteOperation, AddressGroupServiceRestStub): + class _DeleteOperation( + _BaseAddressGroupServiceRestTransport._BaseDeleteOperation, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.DeleteOperation") @@ -2718,27 +3326,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the delete operation method over HTTP. Args: @@ -2753,30 +3362,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseDeleteOperation._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseDeleteOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.DeleteOperation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "DeleteOperation", "httpRequest": http_request, @@ -2785,7 +3406,14 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AddressGroupServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2796,9 +3424,12 @@ def __call__(self, @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(_BaseAddressGroupServiceRestTransport._BaseGetOperation, AddressGroupServiceRestStub): + class _GetOperation( + _BaseAddressGroupServiceRestTransport._BaseGetOperation, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.GetOperation") @@ -2810,27 +3441,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -2848,30 +3480,40 @@ def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseGetOperation._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "GetOperation", "httpRequest": http_request, @@ -2880,7 +3522,14 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AddressGroupServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2891,19 +3540,21 @@ def __call__(self, resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "GetOperation", "httpResponse": http_response, @@ -2914,9 +3565,12 @@ def __call__(self, @property def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(_BaseAddressGroupServiceRestTransport._BaseListOperations, AddressGroupServiceRestStub): + class _ListOperations( + _BaseAddressGroupServiceRestTransport._BaseListOperations, + AddressGroupServiceRestStub, + ): def __hash__(self): return hash("AddressGroupServiceRestTransport.ListOperations") @@ -2928,27 +3582,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. Args: @@ -2966,30 +3621,40 @@ def __call__(self, operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options = _BaseAddressGroupServiceRestTransport._BaseListOperations._get_http_options() + http_options = ( + _BaseAddressGroupServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + transcoded_request = _BaseAddressGroupServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAddressGroupServiceRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseAddressGroupServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.AddressGroupServiceClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "ListOperations", "httpRequest": http_request, @@ -2998,7 +3663,14 @@ def __call__(self, ) # Send the request - response = AddressGroupServiceRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AddressGroupServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3009,19 +3681,21 @@ def __call__(self, resp = operations_pb2.ListOperationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.AddressGroupServiceAsyncClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.AddressGroupService", "rpcName": "ListOperations", "httpResponse": http_response, @@ -3038,6 +3712,4 @@ def close(self): self._session.close() -__all__=( - 'AddressGroupServiceRestTransport', -) +__all__ = ("AddressGroupServiceRestTransport",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py similarity index 52% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py index 86a018236de1..b2b7dd0d0130 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/address_group_service/transports/rest_base.py @@ -14,22 +14,20 @@ # limitations under the License. # import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import AddressGroupServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format -from google.cloud.network_security_v1.types import address_group from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.network_security_v1.types import address_group + +from .base import DEFAULT_CLIENT_INFO, AddressGroupServiceTransport class _BaseAddressGroupServiceRestTransport(AddressGroupServiceTransport): @@ -45,14 +43,16 @@ class _BaseAddressGroupServiceRestTransport(AddressGroupServiceTransport): It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "networksecurity.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -76,7 +76,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -87,27 +89,31 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseAddAddressGroupItems: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{address_group=projects/*/locations/*/addressGroups/*}:addItems', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{address_group=projects/*/locations/*/addressGroups/*}:addItems", + "body": "*", + }, ] return http_options @@ -122,17 +128,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -141,20 +153,24 @@ class _BaseCloneAddressGroupItems: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{address_group=projects/*/locations/*/addressGroups/*}:cloneItems', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{address_group=projects/*/locations/*/addressGroups/*}:cloneItems", + "body": "*", + }, ] return http_options @@ -169,17 +185,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -188,20 +210,26 @@ class _BaseCreateAddressGroup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "addressGroupId" : "", } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "addressGroupId": "", + } @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/addressGroups', - 'body': 'address_group', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/addressGroups", + "body": "address_group", + }, ] return http_options @@ -216,17 +244,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -235,19 +269,23 @@ class _BaseDeleteAddressGroup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/addressGroups/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/addressGroups/*}", + }, ] return http_options @@ -259,11 +297,17 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -272,19 +316,23 @@ class _BaseGetAddressGroup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/addressGroups/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/addressGroups/*}", + }, ] return http_options @@ -296,11 +344,17 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAddressGroupServiceRestTransport._BaseGetAddressGroup._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -309,19 +363,23 @@ class _BaseListAddressGroupReferences: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{address_group=projects/*/locations/*/addressGroups/*}:listReferences', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{address_group=projects/*/locations/*/addressGroups/*}:listReferences", + }, ] return http_options @@ -333,11 +391,17 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -346,19 +410,23 @@ class _BaseListAddressGroups: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/addressGroups', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/addressGroups", + }, ] return http_options @@ -370,11 +438,17 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAddressGroupServiceRestTransport._BaseListAddressGroups._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -383,20 +457,24 @@ class _BaseRemoveAddressGroupItems: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{address_group=projects/*/locations/*/addressGroups/*}:removeItems', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{address_group=projects/*/locations/*/addressGroups/*}:removeItems", + "body": "*", + }, ] return http_options @@ -411,17 +489,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -430,20 +514,24 @@ class _BaseUpdateAddressGroup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{address_group.name=projects/*/locations/*/addressGroups/*}', - 'body': 'address_group', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{address_group.name=projects/*/locations/*/addressGroups/*}", + "body": "address_group", + }, ] return http_options @@ -458,17 +546,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -479,27 +573,27 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseListLocations: @@ -508,27 +602,27 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseGetIamPolicy: @@ -537,39 +631,39 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseSetIamPolicy: @@ -578,48 +672,49 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy", + "body": "*", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) + body = json.dumps(transcoded_request["body"]) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseTestIamPermissions: @@ -628,48 +723,49 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions", + "body": "*", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) + body = json.dumps(transcoded_request["body"]) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseCancelOperation: @@ -678,33 +774,34 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}:cancel", + "body": "*", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) + body = json.dumps(transcoded_request["body"]) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseDeleteOperation: @@ -713,27 +810,27 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseGetOperation: @@ -742,27 +839,27 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseListOperations: @@ -771,30 +868,28 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}/operations', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}/operations", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params -__all__=( - '_BaseAddressGroupServiceRestTransport', -) +__all__ = ("_BaseAddressGroupServiceRestTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest.py index 297de65105b5..e1a74e5ed10c 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest.py @@ -1288,24 +1288,41 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", "body": "*", }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}:cancel", + "body": "*", + }, ], "google.longrunning.Operations.DeleteOperation": [ { "method": "delete", "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, ], "google.longrunning.Operations.GetOperation": [ { "method": "get", "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, ], "google.longrunning.Operations.ListOperations": [ { "method": "get", "uri": "/v1/{name=projects/*/locations/*}/operations", }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}/operations", + }, ], } diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest_base.py index 2bcbdb1f6557..755583cd4433 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/network_security/transports/rest_base.py @@ -892,6 +892,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{name=projects/*/locations/*}", }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}", + }, ] return http_options @@ -917,6 +921,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{name=projects/*}/locations", }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}", + }, ] return http_options @@ -942,6 +950,14 @@ def _get_http_options(): "method": "get", "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", + }, { "method": "get", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", @@ -976,6 +992,16 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", + "body": "*", + }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", @@ -1017,6 +1043,16 @@ def _get_http_options(): "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", "body": "*", }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "body": "*", + }, { "method": "post", "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions", @@ -1058,6 +1094,11 @@ def _get_http_options(): "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", "body": "*", }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}:cancel", + "body": "*", + }, ] return http_options @@ -1088,6 +1129,10 @@ def _get_http_options(): "method": "delete", "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, ] return http_options @@ -1113,6 +1158,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, ] return http_options @@ -1138,6 +1187,10 @@ def _get_http_options(): "method": "get", "uri": "/v1/{name=projects/*/locations/*}/operations", }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}/operations", + }, ] return http_options diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py similarity index 88% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py index a565010ab274..abb884b1320f 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import OrganizationAddressGroupServiceClient from .async_client import OrganizationAddressGroupServiceAsyncClient +from .client import OrganizationAddressGroupServiceClient __all__ = ( - 'OrganizationAddressGroupServiceClient', - 'OrganizationAddressGroupServiceAsyncClient', + "OrganizationAddressGroupServiceClient", + "OrganizationAddressGroupServiceAsyncClient", ) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py similarity index 84% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py index 652742603b03..8935020b7b0d 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/async_client.py @@ -13,21 +13,31 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging as std_logging from collections import OrderedDict +import logging as std_logging import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.network_security_v1 import gapic_version as package_version +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf +from google.cloud.network_security_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -36,29 +46,38 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.services.organization_address_group_service import pagers -from google.cloud.network_security_v1.types import address_group -from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.cloud.network_security_v1.types import common +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import OrganizationAddressGroupServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import OrganizationAddressGroupServiceGrpcAsyncIOTransport + +from google.cloud.network_security_v1.services.organization_address_group_service import ( + pagers, +) +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import common + from .client import OrganizationAddressGroupServiceClient +from .transports.base import ( + DEFAULT_CLIENT_INFO, + OrganizationAddressGroupServiceTransport, +) +from .transports.grpc_asyncio import OrganizationAddressGroupServiceGrpcAsyncIOTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) + class OrganizationAddressGroupServiceAsyncClient: """Organization AddressGroup is created under organization. Requests against Organization AddressGroup will use project from @@ -71,21 +90,47 @@ class OrganizationAddressGroupServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = OrganizationAddressGroupServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE - address_group_path = staticmethod(OrganizationAddressGroupServiceClient.address_group_path) - parse_address_group_path = staticmethod(OrganizationAddressGroupServiceClient.parse_address_group_path) - common_billing_account_path = staticmethod(OrganizationAddressGroupServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(OrganizationAddressGroupServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(OrganizationAddressGroupServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(OrganizationAddressGroupServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(OrganizationAddressGroupServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(OrganizationAddressGroupServiceClient.parse_common_organization_path) - common_project_path = staticmethod(OrganizationAddressGroupServiceClient.common_project_path) - parse_common_project_path = staticmethod(OrganizationAddressGroupServiceClient.parse_common_project_path) - common_location_path = staticmethod(OrganizationAddressGroupServiceClient.common_location_path) - parse_common_location_path = staticmethod(OrganizationAddressGroupServiceClient.parse_common_location_path) + address_group_path = staticmethod( + OrganizationAddressGroupServiceClient.address_group_path + ) + parse_address_group_path = staticmethod( + OrganizationAddressGroupServiceClient.parse_address_group_path + ) + common_billing_account_path = staticmethod( + OrganizationAddressGroupServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + OrganizationAddressGroupServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + OrganizationAddressGroupServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + OrganizationAddressGroupServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + OrganizationAddressGroupServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + OrganizationAddressGroupServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + OrganizationAddressGroupServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + OrganizationAddressGroupServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + OrganizationAddressGroupServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + OrganizationAddressGroupServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -121,7 +166,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -184,12 +231,20 @@ def universe_domain(self) -> str: get_transport_class = OrganizationAddressGroupServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, OrganizationAddressGroupServiceTransport, Callable[..., OrganizationAddressGroupServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + OrganizationAddressGroupServiceTransport, + Callable[..., OrganizationAddressGroupServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the organization address group service async client. Args: @@ -244,31 +299,39 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "credentialsType": None, - } + }, ) - async def list_address_groups(self, - request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAddressGroupsAsyncPager: + async def list_address_groups( + self, + request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupsAsyncPager: r"""Lists address groups in a given project and location. .. code-block:: python @@ -331,10 +394,14 @@ async def sample_list_address_groups(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -348,14 +415,14 @@ async def sample_list_address_groups(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_address_groups] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_address_groups + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -383,14 +450,15 @@ async def sample_list_address_groups(): # Done; return the response. return response - async def get_address_group(self, - request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> address_group.AddressGroup: + async def get_address_group( + self, + request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.AddressGroup: r"""Gets details of a single address group. .. code-block:: python @@ -450,10 +518,14 @@ async def sample_get_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -467,14 +539,14 @@ async def sample_get_address_group(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_address_group] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_address_group + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -491,16 +563,19 @@ async def sample_get_address_group(): # Done; return the response. return response - async def create_address_group(self, - request: Optional[Union[gcn_address_group.CreateAddressGroupRequest, dict]] = None, - *, - parent: Optional[str] = None, - address_group: Optional[gcn_address_group.AddressGroup] = None, - address_group_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def create_address_group( + self, + request: Optional[ + Union[gcn_address_group.CreateAddressGroupRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + address_group: Optional[gcn_address_group.AddressGroup] = None, + address_group_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Creates a new address group in a given project and location. @@ -589,10 +664,14 @@ async def sample_create_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, address_group, address_group_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -610,14 +689,14 @@ async def sample_create_address_group(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_address_group] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_address_group + ] # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -642,15 +721,18 @@ async def sample_create_address_group(): # Done; return the response. return response - async def update_address_group(self, - request: Optional[Union[gcn_address_group.UpdateAddressGroupRequest, dict]] = None, - *, - address_group: Optional[gcn_address_group.AddressGroup] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def update_address_group( + self, + request: Optional[ + Union[gcn_address_group.UpdateAddressGroupRequest, dict] + ] = None, + *, + address_group: Optional[gcn_address_group.AddressGroup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Updates parameters of an address group. .. code-block:: python @@ -730,10 +812,14 @@ async def sample_update_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -749,14 +835,16 @@ async def sample_update_address_group(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_address_group] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_address_group + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group.name", request.address_group.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group.name", request.address_group.name),) + ), ) # Validate the universe domain. @@ -781,15 +869,18 @@ async def sample_update_address_group(): # Done; return the response. return response - async def add_address_group_items(self, - request: Optional[Union[gcn_address_group.AddAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - items: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def add_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.AddAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Adds items to an address group. .. code-block:: python @@ -860,10 +951,14 @@ async def sample_add_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, items] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -879,14 +974,16 @@ async def sample_add_address_group_items(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.add_address_group_items] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.add_address_group_items + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -911,15 +1008,18 @@ async def sample_add_address_group_items(): # Done; return the response. return response - async def remove_address_group_items(self, - request: Optional[Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - items: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def remove_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Removes items from an address group. .. code-block:: python @@ -990,10 +1090,14 @@ async def sample_remove_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, items] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1009,14 +1113,16 @@ async def sample_remove_address_group_items(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.remove_address_group_items] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.remove_address_group_items + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1041,15 +1147,18 @@ async def sample_remove_address_group_items(): # Done; return the response. return response - async def clone_address_group_items(self, - request: Optional[Union[gcn_address_group.CloneAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - source_address_group: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def clone_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.CloneAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + source_address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Clones items from one address group to another. .. code-block:: python @@ -1122,10 +1231,14 @@ async def sample_clone_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, source_address_group] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1141,14 +1254,16 @@ async def sample_clone_address_group_items(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.clone_address_group_items] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.clone_address_group_items + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1173,14 +1288,15 @@ async def sample_clone_address_group_items(): # Done; return the response. return response - async def delete_address_group(self, - request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: + async def delete_address_group( + self, + request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: r"""Deletes an address group. .. code-block:: python @@ -1253,10 +1369,14 @@ async def sample_delete_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1270,14 +1390,14 @@ async def sample_delete_address_group(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_address_group] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_address_group + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1302,14 +1422,17 @@ async def sample_delete_address_group(): # Done; return the response. return response - async def list_address_group_references(self, - request: Optional[Union[gcn_address_group.ListAddressGroupReferencesRequest, dict]] = None, - *, - address_group: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAddressGroupReferencesAsyncPager: + async def list_address_group_references( + self, + request: Optional[ + Union[gcn_address_group.ListAddressGroupReferencesRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupReferencesAsyncPager: r"""Lists references of an address group. .. code-block:: python @@ -1372,10 +1495,14 @@ async def sample_list_address_group_references(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1389,14 +1516,16 @@ async def sample_list_address_group_references(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_address_group_references] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_address_group_references + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1462,8 +1591,7 @@ async def list_operations( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1471,7 +1599,11 @@ async def list_operations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1514,8 +1646,7 @@ async def get_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1523,7 +1654,11 @@ async def get_operation( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1570,15 +1705,19 @@ async def delete_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def cancel_operation( self, @@ -1621,15 +1760,19 @@ async def cancel_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) async def set_iam_policy( self, @@ -1735,8 +1878,7 @@ async def set_iam_policy( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -1744,7 +1886,11 @@ async def set_iam_policy( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1854,8 +2000,7 @@ async def get_iam_policy( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -1863,7 +2008,11 @@ async def get_iam_policy( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1906,13 +2055,14 @@ async def test_iam_permissions( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -1920,7 +2070,11 @@ async def test_iam_permissions( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1963,8 +2117,7 @@ async def get_location( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1972,7 +2125,11 @@ async def get_location( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2015,8 +2172,7 @@ async def list_locations( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2024,7 +2180,11 @@ async def list_locations( # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2035,12 +2195,13 @@ async def __aenter__(self) -> "OrganizationAddressGroupServiceAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "OrganizationAddressGroupServiceAsyncClient", -) +__all__ = ("OrganizationAddressGroupServiceAsyncClient",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/client.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/client.py similarity index 83% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/client.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/client.py index 04bdc599ac71..ee91fcacd0d1 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/client.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/client.py @@ -19,22 +19,34 @@ import logging as std_logging import os import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) import warnings -from google.cloud.network_security_v1 import gapic_version as package_version - from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf +from google.cloud.network_security_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -50,18 +63,25 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.services.organization_address_group_service import pagers -from google.cloud.network_security_v1.types import address_group -from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.cloud.network_security_v1.types import common +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import OrganizationAddressGroupServiceTransport, DEFAULT_CLIENT_INFO + +from google.cloud.network_security_v1.services.organization_address_group_service import ( + pagers, +) +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import common + +from .transports.base import ( + DEFAULT_CLIENT_INFO, + OrganizationAddressGroupServiceTransport, +) from .transports.grpc import OrganizationAddressGroupServiceGrpcTransport from .transports.grpc_asyncio import OrganizationAddressGroupServiceGrpcAsyncIOTransport from .transports.rest import OrganizationAddressGroupServiceRestTransport @@ -74,14 +94,20 @@ class OrganizationAddressGroupServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[OrganizationAddressGroupServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[OrganizationAddressGroupServiceTransport]] _transport_registry["grpc"] = OrganizationAddressGroupServiceGrpcTransport - _transport_registry["grpc_asyncio"] = OrganizationAddressGroupServiceGrpcAsyncIOTransport + _transport_registry[ + "grpc_asyncio" + ] = OrganizationAddressGroupServiceGrpcAsyncIOTransport _transport_registry["rest"] = OrganizationAddressGroupServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[OrganizationAddressGroupServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[OrganizationAddressGroupServiceTransport]: """Returns an appropriate transport class. Args: @@ -100,7 +126,9 @@ def get_transport_class(cls, return next(iter(cls._transport_registry.values())) -class OrganizationAddressGroupServiceClient(metaclass=OrganizationAddressGroupServiceClientMeta): +class OrganizationAddressGroupServiceClient( + metaclass=OrganizationAddressGroupServiceClientMeta +): """Organization AddressGroup is created under organization. Requests against Organization AddressGroup will use project from request credential for activation/quota/visibility check. @@ -176,8 +204,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: OrganizationAddressGroupServiceClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -194,73 +221,108 @@ def transport(self) -> OrganizationAddressGroupServiceTransport: return self._transport @staticmethod - def address_group_path(project: str,location: str,address_group: str,) -> str: + def address_group_path( + project: str, + location: str, + address_group: str, + ) -> str: """Returns a fully-qualified address_group string.""" - return "projects/{project}/locations/{location}/addressGroups/{address_group}".format(project=project, location=location, address_group=address_group, ) + return "projects/{project}/locations/{location}/addressGroups/{address_group}".format( + project=project, + location=location, + address_group=address_group, + ) @staticmethod - def parse_address_group_path(path: str) -> Dict[str,str]: + def parse_address_group_path(path: str) -> Dict[str, str]: """Parses a address_group path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/addressGroups/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/addressGroups/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + 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, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + 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: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + 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: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + 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: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Deprecated. Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -292,16 +354,22 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio google.auth.exceptions.MutualTLSChannelError: If any errors happen. """ - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) if client_options is None: client_options = client_options_lib.ClientOptions() use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Figure out the client cert source to use. client_cert_source = None @@ -314,7 +382,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -335,13 +405,19 @@ def _read_environment_variables(): google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT is not any of ["auto", "never", "always"]. """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) return use_client_cert == "true", use_mtls_endpoint, universe_domain_env @staticmethod @@ -364,7 +440,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): """Return the API endpoint used by the client. Args: @@ -380,17 +458,27 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) api_endpoint = OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -426,15 +514,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -467,12 +558,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, OrganizationAddressGroupServiceTransport, Callable[..., OrganizationAddressGroupServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + OrganizationAddressGroupServiceTransport, + Callable[..., OrganizationAddressGroupServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the organization address group service client. Args: @@ -527,14 +626,28 @@ def __init__(self, *, self._client_options = client_options_lib.from_dict(self._client_options) if self._client_options is None: self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + universe_domain_opt = getattr(self._client_options, "universe_domain", None) - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = OrganizationAddressGroupServiceClient._read_environment_variables() - self._client_cert_source = OrganizationAddressGroupServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = OrganizationAddressGroupServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = OrganizationAddressGroupServiceClient._read_environment_variables() + self._client_cert_source = ( + OrganizationAddressGroupServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = ( + OrganizationAddressGroupServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + ) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -545,17 +658,23 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, OrganizationAddressGroupServiceTransport) + transport_provided = isinstance( + transport, OrganizationAddressGroupServiceTransport + ) if transport_provided: # transport is a OrganizationAddressGroupServiceTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -564,23 +683,35 @@ def __init__(self, *, self._transport = cast(OrganizationAddressGroupServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - OrganizationAddressGroupServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or OrganizationAddressGroupServiceClient._get_api_endpoint( self._client_options.api_endpoint, self._client_cert_source, self._universe_domain, - self._use_mtls_endpoint)) + self._use_mtls_endpoint, + ) + ) if not transport_provided: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) - transport_init: Union[Type[OrganizationAddressGroupServiceTransport], Callable[..., OrganizationAddressGroupServiceTransport]] = ( + transport_init: Union[ + Type[OrganizationAddressGroupServiceTransport], + Callable[..., OrganizationAddressGroupServiceTransport], + ] = ( OrganizationAddressGroupServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None - else cast(Callable[..., OrganizationAddressGroupServiceTransport], transport) + else cast( + Callable[..., OrganizationAddressGroupServiceTransport], transport + ) ) # initialize with the provided callable or the passed in class self._transport = transport_init( @@ -596,28 +727,37 @@ def __init__(self, *, ) if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER _LOGGER.debug( "Created client `google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient`.", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "credentialsType": None, - } + }, ) - def list_address_groups(self, - request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAddressGroupsPager: + def list_address_groups( + self, + request: Optional[Union[address_group.ListAddressGroupsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupsPager: r"""Lists address groups in a given project and location. .. code-block:: python @@ -680,10 +820,14 @@ def sample_list_address_groups(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -701,9 +845,7 @@ def sample_list_address_groups(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -731,14 +873,15 @@ def sample_list_address_groups(): # Done; return the response. return response - def get_address_group(self, - request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> address_group.AddressGroup: + def get_address_group( + self, + request: Optional[Union[address_group.GetAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.AddressGroup: r"""Gets details of a single address group. .. code-block:: python @@ -798,10 +941,14 @@ def sample_get_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -819,9 +966,7 @@ def sample_get_address_group(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -838,16 +983,19 @@ def sample_get_address_group(): # Done; return the response. return response - def create_address_group(self, - request: Optional[Union[gcn_address_group.CreateAddressGroupRequest, dict]] = None, - *, - parent: Optional[str] = None, - address_group: Optional[gcn_address_group.AddressGroup] = None, - address_group_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def create_address_group( + self, + request: Optional[ + Union[gcn_address_group.CreateAddressGroupRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + address_group: Optional[gcn_address_group.AddressGroup] = None, + address_group_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Creates a new address group in a given project and location. @@ -936,10 +1084,14 @@ def sample_create_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, address_group, address_group_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -961,9 +1113,7 @@ def sample_create_address_group(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -988,15 +1138,18 @@ def sample_create_address_group(): # Done; return the response. return response - def update_address_group(self, - request: Optional[Union[gcn_address_group.UpdateAddressGroupRequest, dict]] = None, - *, - address_group: Optional[gcn_address_group.AddressGroup] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def update_address_group( + self, + request: Optional[ + Union[gcn_address_group.UpdateAddressGroupRequest, dict] + ] = None, + *, + address_group: Optional[gcn_address_group.AddressGroup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Updates parameters of an address group. .. code-block:: python @@ -1076,10 +1229,14 @@ def sample_update_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1099,9 +1256,9 @@ def sample_update_address_group(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group.name", request.address_group.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group.name", request.address_group.name),) + ), ) # Validate the universe domain. @@ -1126,15 +1283,18 @@ def sample_update_address_group(): # Done; return the response. return response - def add_address_group_items(self, - request: Optional[Union[gcn_address_group.AddAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - items: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def add_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.AddAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Adds items to an address group. .. code-block:: python @@ -1205,10 +1365,14 @@ def sample_add_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, items] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1228,9 +1392,9 @@ def sample_add_address_group_items(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1255,15 +1419,18 @@ def sample_add_address_group_items(): # Done; return the response. return response - def remove_address_group_items(self, - request: Optional[Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - items: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def remove_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.RemoveAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + items: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Removes items from an address group. .. code-block:: python @@ -1334,10 +1501,14 @@ def sample_remove_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, items] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1352,14 +1523,16 @@ def sample_remove_address_group_items(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.remove_address_group_items] + rpc = self._transport._wrapped_methods[ + self._transport.remove_address_group_items + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1384,15 +1557,18 @@ def sample_remove_address_group_items(): # Done; return the response. return response - def clone_address_group_items(self, - request: Optional[Union[gcn_address_group.CloneAddressGroupItemsRequest, dict]] = None, - *, - address_group: Optional[str] = None, - source_address_group: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def clone_address_group_items( + self, + request: Optional[ + Union[gcn_address_group.CloneAddressGroupItemsRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + source_address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Clones items from one address group to another. .. code-block:: python @@ -1465,10 +1641,14 @@ def sample_clone_address_group_items(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group, source_address_group] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1483,14 +1663,16 @@ def sample_clone_address_group_items(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.clone_address_group_items] + rpc = self._transport._wrapped_methods[ + self._transport.clone_address_group_items + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1515,14 +1697,15 @@ def sample_clone_address_group_items(): # Done; return the response. return response - def delete_address_group(self, - request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: + def delete_address_group( + self, + request: Optional[Union[address_group.DeleteAddressGroupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: r"""Deletes an address group. .. code-block:: python @@ -1595,10 +1778,14 @@ def sample_delete_address_group(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1616,9 +1803,7 @@ def sample_delete_address_group(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1643,14 +1828,17 @@ def sample_delete_address_group(): # Done; return the response. return response - def list_address_group_references(self, - request: Optional[Union[gcn_address_group.ListAddressGroupReferencesRequest, dict]] = None, - *, - address_group: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAddressGroupReferencesPager: + def list_address_group_references( + self, + request: Optional[ + Union[gcn_address_group.ListAddressGroupReferencesRequest, dict] + ] = None, + *, + address_group: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAddressGroupReferencesPager: r"""Lists references of an address group. .. code-block:: python @@ -1713,10 +1901,14 @@ def sample_list_address_group_references(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [address_group] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1729,14 +1921,16 @@ def sample_list_address_group_references(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_address_group_references] + rpc = self._transport._wrapped_methods[ + self._transport.list_address_group_references + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("address_group", request.address_group), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("address_group", request.address_group),) + ), ) # Validate the universe domain. @@ -1815,8 +2009,7 @@ def list_operations( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1825,7 +2018,11 @@ def list_operations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1871,8 +2068,7 @@ def get_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1881,7 +2077,11 @@ def get_operation( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1931,15 +2131,19 @@ def delete_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def cancel_operation( self, @@ -1982,15 +2186,19 @@ def cancel_operation( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) def set_iam_policy( self, @@ -2096,8 +2304,7 @@ def set_iam_policy( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -2106,7 +2313,11 @@ def set_iam_policy( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2219,8 +2430,7 @@ def get_iam_policy( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -2229,7 +2439,11 @@ def get_iam_policy( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2280,8 +2494,7 @@ def test_iam_permissions( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Validate the universe domain. @@ -2290,7 +2503,11 @@ def test_iam_permissions( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2336,8 +2553,7 @@ def get_location( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2346,7 +2562,11 @@ def get_location( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2392,8 +2612,7 @@ def list_locations( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -2402,7 +2621,11 @@ def list_locations( try: # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -2411,11 +2634,11 @@ def list_locations( raise e -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ -__all__ = ( - "OrganizationAddressGroupServiceClient", -) +__all__ = ("OrganizationAddressGroupServiceClient",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/pagers.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/pagers.py similarity index 76% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/pagers.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/pagers.py index 4c8ac9f092ff..1798baeb1630 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/address_group_service/pagers.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/pagers.py @@ -13,19 +13,33 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore -from google.cloud.network_security_v1.types import address_group from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import address_group class ListAddressGroupsPager: @@ -45,14 +59,17 @@ class ListAddressGroupsPager: 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[..., address_group.ListAddressGroupsResponse], - request: address_group.ListAddressGroupsRequest, - response: address_group.ListAddressGroupsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + + def __init__( + self, + method: Callable[..., address_group.ListAddressGroupsResponse], + request: address_group.ListAddressGroupsRequest, + response: address_group.ListAddressGroupsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): """Instantiate the pager. Args: @@ -85,7 +102,12 @@ def pages(self) -> Iterator[address_group.ListAddressGroupsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) yield self._response def __iter__(self) -> Iterator[address_group.AddressGroup]: @@ -93,7 +115,7 @@ def __iter__(self) -> Iterator[address_group.AddressGroup]: yield from page.address_groups def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListAddressGroupsAsyncPager: @@ -113,14 +135,17 @@ class ListAddressGroupsAsyncPager: 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[address_group.ListAddressGroupsResponse]], - request: address_group.ListAddressGroupsRequest, - response: address_group.ListAddressGroupsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + + def __init__( + self, + method: Callable[..., Awaitable[address_group.ListAddressGroupsResponse]], + request: address_group.ListAddressGroupsRequest, + response: address_group.ListAddressGroupsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): """Instantiates the pager. Args: @@ -153,8 +178,14 @@ async def pages(self) -> AsyncIterator[address_group.ListAddressGroupsResponse]: 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) yield self._response + def __aiter__(self) -> AsyncIterator[address_group.AddressGroup]: async def async_generator(): async for page in self.pages: @@ -164,7 +195,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListAddressGroupReferencesPager: @@ -184,14 +215,17 @@ class ListAddressGroupReferencesPager: 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[..., gcn_address_group.ListAddressGroupReferencesResponse], - request: gcn_address_group.ListAddressGroupReferencesRequest, - response: gcn_address_group.ListAddressGroupReferencesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + + def __init__( + self, + method: Callable[..., gcn_address_group.ListAddressGroupReferencesResponse], + request: gcn_address_group.ListAddressGroupReferencesRequest, + response: gcn_address_group.ListAddressGroupReferencesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): """Instantiate the pager. Args: @@ -224,15 +258,24 @@ def pages(self) -> Iterator[gcn_address_group.ListAddressGroupReferencesResponse yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) yield self._response - def __iter__(self) -> Iterator[gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference]: + def __iter__( + self, + ) -> Iterator[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference + ]: for page in self.pages: yield from page.address_group_references def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListAddressGroupReferencesAsyncPager: @@ -252,14 +295,19 @@ class ListAddressGroupReferencesAsyncPager: 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[gcn_address_group.ListAddressGroupReferencesResponse]], - request: gcn_address_group.ListAddressGroupReferencesRequest, - response: gcn_address_group.ListAddressGroupReferencesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): + + def __init__( + self, + method: Callable[ + ..., Awaitable[gcn_address_group.ListAddressGroupReferencesResponse] + ], + request: gcn_address_group.ListAddressGroupReferencesRequest, + response: gcn_address_group.ListAddressGroupReferencesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): """Instantiates the pager. Args: @@ -288,13 +336,25 @@ def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property - async def pages(self) -> AsyncIterator[gcn_address_group.ListAddressGroupReferencesResponse]: + async def pages( + self, + ) -> AsyncIterator[gcn_address_group.ListAddressGroupReferencesResponse]: 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) yield self._response - def __aiter__(self) -> AsyncIterator[gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference]: + + def __aiter__( + self, + ) -> AsyncIterator[ + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference + ]: async def async_generator(): async for page in self.pages: for response in page.address_group_references: @@ -303,4 +363,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/README.rst b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/README.rst rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/README.rst diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py similarity index 56% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py index a76ca8cbee11..5ac24e1c75ff 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/__init__.py @@ -19,20 +19,25 @@ from .base import OrganizationAddressGroupServiceTransport from .grpc import OrganizationAddressGroupServiceGrpcTransport from .grpc_asyncio import OrganizationAddressGroupServiceGrpcAsyncIOTransport -from .rest import OrganizationAddressGroupServiceRestTransport -from .rest import OrganizationAddressGroupServiceRestInterceptor - +from .rest import ( + OrganizationAddressGroupServiceRestInterceptor, + OrganizationAddressGroupServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[OrganizationAddressGroupServiceTransport]] -_transport_registry['grpc'] = OrganizationAddressGroupServiceGrpcTransport -_transport_registry['grpc_asyncio'] = OrganizationAddressGroupServiceGrpcAsyncIOTransport -_transport_registry['rest'] = OrganizationAddressGroupServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[OrganizationAddressGroupServiceTransport]] +_transport_registry["grpc"] = OrganizationAddressGroupServiceGrpcTransport +_transport_registry[ + "grpc_asyncio" +] = OrganizationAddressGroupServiceGrpcAsyncIOTransport +_transport_registry["rest"] = OrganizationAddressGroupServiceRestTransport __all__ = ( - 'OrganizationAddressGroupServiceTransport', - 'OrganizationAddressGroupServiceGrpcTransport', - 'OrganizationAddressGroupServiceGrpcAsyncIOTransport', - 'OrganizationAddressGroupServiceRestTransport', - 'OrganizationAddressGroupServiceRestInterceptor', + "OrganizationAddressGroupServiceTransport", + "OrganizationAddressGroupServiceGrpcTransport", + "OrganizationAddressGroupServiceGrpcAsyncIOTransport", + "OrganizationAddressGroupServiceRestTransport", + "OrganizationAddressGroupServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py similarity index 69% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py index 76cbe0a76417..d17125c0c730 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/base.py @@ -16,26 +16,26 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.network_security_v1 import gapic_version as package_version - -import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore import google.protobuf -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1 import gapic_version as package_version from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.network_security_v1.types import address_group -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -44,24 +44,23 @@ class OrganizationAddressGroupServiceTransport(abc.ABC): """Abstract transport class for OrganizationAddressGroupService.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - DEFAULT_HOST: str = 'networksecurity.googleapis.com' + DEFAULT_HOST: str = "networksecurity.googleapis.com" def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: """Instantiate the transport. Args: @@ -97,30 +96,38 @@ def __init__( # 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") + 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 - ) + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): credentials = credentials.with_always_use_jwt_access(True) # Save the credentials. self._credentials = credentials # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host @property @@ -220,14 +227,14 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -237,84 +244,90 @@ def operations_client(self): raise NotImplementedError() @property - def list_address_groups(self) -> Callable[ - [address_group.ListAddressGroupsRequest], - Union[ - address_group.ListAddressGroupsResponse, - Awaitable[address_group.ListAddressGroupsResponse] - ]]: + def list_address_groups( + self, + ) -> Callable[ + [address_group.ListAddressGroupsRequest], + Union[ + address_group.ListAddressGroupsResponse, + Awaitable[address_group.ListAddressGroupsResponse], + ], + ]: raise NotImplementedError() @property - def get_address_group(self) -> Callable[ - [address_group.GetAddressGroupRequest], - Union[ - address_group.AddressGroup, - Awaitable[address_group.AddressGroup] - ]]: + def get_address_group( + self, + ) -> Callable[ + [address_group.GetAddressGroupRequest], + Union[address_group.AddressGroup, Awaitable[address_group.AddressGroup]], + ]: raise NotImplementedError() @property - def create_address_group(self) -> Callable[ - [gcn_address_group.CreateAddressGroupRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_address_group( + self, + ) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_address_group(self) -> Callable[ - [gcn_address_group.UpdateAddressGroupRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def update_address_group( + self, + ) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def add_address_group_items(self) -> Callable[ - [gcn_address_group.AddAddressGroupItemsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def add_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def remove_address_group_items(self) -> Callable[ - [gcn_address_group.RemoveAddressGroupItemsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def remove_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def clone_address_group_items(self) -> Callable[ - [gcn_address_group.CloneAddressGroupItemsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def clone_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_address_group(self) -> Callable[ - [address_group.DeleteAddressGroupRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_address_group( + self, + ) -> Callable[ + [address_group.DeleteAddressGroupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def list_address_group_references(self) -> Callable[ - [gcn_address_group.ListAddressGroupReferencesRequest], - Union[ - gcn_address_group.ListAddressGroupReferencesResponse, - Awaitable[gcn_address_group.ListAddressGroupReferencesResponse] - ]]: + def list_address_group_references( + self, + ) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + Union[ + gcn_address_group.ListAddressGroupReferencesResponse, + Awaitable[gcn_address_group.ListAddressGroupReferencesResponse], + ], + ]: raise NotImplementedError() @property @@ -322,7 +335,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -338,19 +354,13 @@ def get_operation( @property def cancel_operation( self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: raise NotImplementedError() @property def delete_operation( self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: raise NotImplementedError() @property @@ -384,7 +394,8 @@ def test_iam_permissions( raise NotImplementedError() @property - def get_location(self, + def get_location( + self, ) -> Callable[ [locations_pb2.GetLocationRequest], Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], @@ -392,10 +403,14 @@ def get_location(self, raise NotImplementedError() @property - def list_locations(self, + def list_locations( + self, ) -> Callable[ [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], ]: raise NotImplementedError() @@ -404,6 +419,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'OrganizationAddressGroupServiceTransport', -) +__all__ = ("OrganizationAddressGroupServiceTransport",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py similarity index 81% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py index ef0c38ea6214..99ccf01bcddc 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc.py @@ -16,31 +16,30 @@ import json import logging as std_logging import pickle -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.types import address_group from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import OrganizationAddressGroupServiceTransport, DEFAULT_CLIENT_INFO +from google.cloud.network_security_v1.types import address_group + +from .base import DEFAULT_CLIENT_INFO, OrganizationAddressGroupServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -50,7 +49,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -71,7 +72,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -82,7 +83,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -97,7 +102,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": client_call_details.method, "response": grpc_response, @@ -107,7 +112,9 @@ def intercept_unary_unary(self, continuation, client_call_details, request): return response -class OrganizationAddressGroupServiceGrpcTransport(OrganizationAddressGroupServiceTransport): +class OrganizationAddressGroupServiceGrpcTransport( + OrganizationAddressGroupServiceTransport +): """gRPC backend transport for OrganizationAddressGroupService. Organization AddressGroup is created under organization. @@ -121,23 +128,26 @@ class OrganizationAddressGroupServiceGrpcTransport(OrganizationAddressGroupServi 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 = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -260,19 +270,23 @@ def __init__(self, *, ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: + def create_channel( + cls, + host: str = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: """Create and return a gRPC channel object. Args: host (Optional[str]): The host for the channel to use. @@ -307,13 +321,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -333,9 +346,12 @@ def operations_client(self) -> operations_v1.OperationsClient: return self._operations_client @property - def list_address_groups(self) -> Callable[ - [address_group.ListAddressGroupsRequest], - address_group.ListAddressGroupsResponse]: + def list_address_groups( + self, + ) -> Callable[ + [address_group.ListAddressGroupsRequest], + address_group.ListAddressGroupsResponse, + ]: r"""Return a callable for the list address groups method over gRPC. Lists address groups in a given project and location. @@ -350,18 +366,18 @@ def list_address_groups(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_address_groups' not in self._stubs: - self._stubs['list_address_groups'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroups', + if "list_address_groups" not in self._stubs: + self._stubs["list_address_groups"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroups", request_serializer=address_group.ListAddressGroupsRequest.serialize, response_deserializer=address_group.ListAddressGroupsResponse.deserialize, ) - return self._stubs['list_address_groups'] + return self._stubs["list_address_groups"] @property - def get_address_group(self) -> Callable[ - [address_group.GetAddressGroupRequest], - address_group.AddressGroup]: + def get_address_group( + self, + ) -> Callable[[address_group.GetAddressGroupRequest], address_group.AddressGroup]: r"""Return a callable for the get address group method over gRPC. Gets details of a single address group. @@ -376,18 +392,20 @@ def get_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_address_group' not in self._stubs: - self._stubs['get_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/GetAddressGroup', + if "get_address_group" not in self._stubs: + self._stubs["get_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/GetAddressGroup", request_serializer=address_group.GetAddressGroupRequest.serialize, response_deserializer=address_group.AddressGroup.deserialize, ) - return self._stubs['get_address_group'] + return self._stubs["get_address_group"] @property - def create_address_group(self) -> Callable[ - [gcn_address_group.CreateAddressGroupRequest], - operations_pb2.Operation]: + def create_address_group( + self, + ) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], operations_pb2.Operation + ]: r"""Return a callable for the create address group method over gRPC. Creates a new address group in a given project and @@ -403,18 +421,20 @@ def create_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_address_group' not in self._stubs: - self._stubs['create_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CreateAddressGroup', + if "create_address_group" not in self._stubs: + self._stubs["create_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CreateAddressGroup", request_serializer=gcn_address_group.CreateAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_address_group'] + return self._stubs["create_address_group"] @property - def update_address_group(self) -> Callable[ - [gcn_address_group.UpdateAddressGroupRequest], - operations_pb2.Operation]: + def update_address_group( + self, + ) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], operations_pb2.Operation + ]: r"""Return a callable for the update address group method over gRPC. Updates parameters of an address group. @@ -429,18 +449,20 @@ def update_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_address_group' not in self._stubs: - self._stubs['update_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/UpdateAddressGroup', + if "update_address_group" not in self._stubs: + self._stubs["update_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/UpdateAddressGroup", request_serializer=gcn_address_group.UpdateAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_address_group'] + return self._stubs["update_address_group"] @property - def add_address_group_items(self) -> Callable[ - [gcn_address_group.AddAddressGroupItemsRequest], - operations_pb2.Operation]: + def add_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], operations_pb2.Operation + ]: r"""Return a callable for the add address group items method over gRPC. Adds items to an address group. @@ -455,18 +477,20 @@ def add_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'add_address_group_items' not in self._stubs: - self._stubs['add_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/AddAddressGroupItems', + if "add_address_group_items" not in self._stubs: + self._stubs["add_address_group_items"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/AddAddressGroupItems", request_serializer=gcn_address_group.AddAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['add_address_group_items'] + return self._stubs["add_address_group_items"] @property - def remove_address_group_items(self) -> Callable[ - [gcn_address_group.RemoveAddressGroupItemsRequest], - operations_pb2.Operation]: + def remove_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], operations_pb2.Operation + ]: r"""Return a callable for the remove address group items method over gRPC. Removes items from an address group. @@ -481,18 +505,22 @@ def remove_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'remove_address_group_items' not in self._stubs: - self._stubs['remove_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/RemoveAddressGroupItems', + if "remove_address_group_items" not in self._stubs: + self._stubs[ + "remove_address_group_items" + ] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/RemoveAddressGroupItems", request_serializer=gcn_address_group.RemoveAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['remove_address_group_items'] + return self._stubs["remove_address_group_items"] @property - def clone_address_group_items(self) -> Callable[ - [gcn_address_group.CloneAddressGroupItemsRequest], - operations_pb2.Operation]: + def clone_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], operations_pb2.Operation + ]: r"""Return a callable for the clone address group items method over gRPC. Clones items from one address group to another. @@ -507,18 +535,18 @@ def clone_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'clone_address_group_items' not in self._stubs: - self._stubs['clone_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CloneAddressGroupItems', + if "clone_address_group_items" not in self._stubs: + self._stubs["clone_address_group_items"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CloneAddressGroupItems", request_serializer=gcn_address_group.CloneAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['clone_address_group_items'] + return self._stubs["clone_address_group_items"] @property - def delete_address_group(self) -> Callable[ - [address_group.DeleteAddressGroupRequest], - operations_pb2.Operation]: + def delete_address_group( + self, + ) -> Callable[[address_group.DeleteAddressGroupRequest], operations_pb2.Operation]: r"""Return a callable for the delete address group method over gRPC. Deletes an address group. @@ -533,18 +561,21 @@ def delete_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_address_group' not in self._stubs: - self._stubs['delete_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/DeleteAddressGroup', + if "delete_address_group" not in self._stubs: + self._stubs["delete_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/DeleteAddressGroup", request_serializer=address_group.DeleteAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_address_group'] + return self._stubs["delete_address_group"] @property - def list_address_group_references(self) -> Callable[ - [gcn_address_group.ListAddressGroupReferencesRequest], - gcn_address_group.ListAddressGroupReferencesResponse]: + def list_address_group_references( + self, + ) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + gcn_address_group.ListAddressGroupReferencesResponse, + ]: r"""Return a callable for the list address group references method over gRPC. Lists references of an address group. @@ -559,13 +590,15 @@ def list_address_group_references(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_address_group_references' not in self._stubs: - self._stubs['list_address_group_references'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroupReferences', + if "list_address_group_references" not in self._stubs: + self._stubs[ + "list_address_group_references" + ] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroupReferences", request_serializer=gcn_address_group.ListAddressGroupReferencesRequest.serialize, response_deserializer=gcn_address_group.ListAddressGroupReferencesResponse.deserialize, ) - return self._stubs['list_address_group_references'] + return self._stubs["list_address_group_references"] def close(self): self._logged_channel.close() @@ -574,8 +607,7 @@ def close(self): def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ + r"""Return a callable for the delete_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -592,8 +624,7 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -610,8 +641,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -627,9 +657,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -645,9 +676,10 @@ def list_operations( @property def list_locations( self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -664,8 +696,7 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -733,7 +764,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. Tests the specified permissions against the IAM access control @@ -762,6 +794,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'OrganizationAddressGroupServiceGrpcTransport', -) +__all__ = ("OrganizationAddressGroupServiceGrpcTransport",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py similarity index 82% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py index 4162831caf0e..7c7fb1c555c0 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/grpc_asyncio.py @@ -15,36 +15,35 @@ # import inspect import json -import pickle import logging as std_logging -import warnings +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.protobuf.json_format import MessageToJson import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.cloud.network_security_v1.types import address_group from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import OrganizationAddressGroupServiceTransport, DEFAULT_CLIENT_INFO +from google.cloud.network_security_v1.types import address_group + +from .base import DEFAULT_CLIENT_INFO, OrganizationAddressGroupServiceTransport from .grpc import OrganizationAddressGroupServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -52,9 +51,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -75,7 +78,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -86,7 +89,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -101,7 +108,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -111,7 +118,9 @@ async def intercept_unary_unary(self, continuation, client_call_details, request return response -class OrganizationAddressGroupServiceGrpcAsyncIOTransport(OrganizationAddressGroupServiceTransport): +class OrganizationAddressGroupServiceGrpcAsyncIOTransport( + OrganizationAddressGroupServiceTransport +): """gRPC AsyncIO backend transport for OrganizationAddressGroupService. Organization AddressGroup is created under organization. @@ -130,13 +139,15 @@ class OrganizationAddressGroupServiceGrpcAsyncIOTransport(OrganizationAddressGro _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: + def create_channel( + cls, + host: str = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. @@ -166,24 +177,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -308,7 +321,9 @@ def __init__(self, *, self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -339,9 +354,12 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def list_address_groups(self) -> Callable[ - [address_group.ListAddressGroupsRequest], - Awaitable[address_group.ListAddressGroupsResponse]]: + def list_address_groups( + self, + ) -> Callable[ + [address_group.ListAddressGroupsRequest], + Awaitable[address_group.ListAddressGroupsResponse], + ]: r"""Return a callable for the list address groups method over gRPC. Lists address groups in a given project and location. @@ -356,18 +374,20 @@ def list_address_groups(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_address_groups' not in self._stubs: - self._stubs['list_address_groups'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroups', + if "list_address_groups" not in self._stubs: + self._stubs["list_address_groups"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroups", request_serializer=address_group.ListAddressGroupsRequest.serialize, response_deserializer=address_group.ListAddressGroupsResponse.deserialize, ) - return self._stubs['list_address_groups'] + return self._stubs["list_address_groups"] @property - def get_address_group(self) -> Callable[ - [address_group.GetAddressGroupRequest], - Awaitable[address_group.AddressGroup]]: + def get_address_group( + self, + ) -> Callable[ + [address_group.GetAddressGroupRequest], Awaitable[address_group.AddressGroup] + ]: r"""Return a callable for the get address group method over gRPC. Gets details of a single address group. @@ -382,18 +402,21 @@ def get_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_address_group' not in self._stubs: - self._stubs['get_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/GetAddressGroup', + if "get_address_group" not in self._stubs: + self._stubs["get_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/GetAddressGroup", request_serializer=address_group.GetAddressGroupRequest.serialize, response_deserializer=address_group.AddressGroup.deserialize, ) - return self._stubs['get_address_group'] + return self._stubs["get_address_group"] @property - def create_address_group(self) -> Callable[ - [gcn_address_group.CreateAddressGroupRequest], - Awaitable[operations_pb2.Operation]]: + def create_address_group( + self, + ) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], + Awaitable[operations_pb2.Operation], + ]: r"""Return a callable for the create address group method over gRPC. Creates a new address group in a given project and @@ -409,18 +432,21 @@ def create_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_address_group' not in self._stubs: - self._stubs['create_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CreateAddressGroup', + if "create_address_group" not in self._stubs: + self._stubs["create_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CreateAddressGroup", request_serializer=gcn_address_group.CreateAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_address_group'] + return self._stubs["create_address_group"] @property - def update_address_group(self) -> Callable[ - [gcn_address_group.UpdateAddressGroupRequest], - Awaitable[operations_pb2.Operation]]: + def update_address_group( + self, + ) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], + Awaitable[operations_pb2.Operation], + ]: r"""Return a callable for the update address group method over gRPC. Updates parameters of an address group. @@ -435,18 +461,21 @@ def update_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_address_group' not in self._stubs: - self._stubs['update_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/UpdateAddressGroup', + if "update_address_group" not in self._stubs: + self._stubs["update_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/UpdateAddressGroup", request_serializer=gcn_address_group.UpdateAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['update_address_group'] + return self._stubs["update_address_group"] @property - def add_address_group_items(self) -> Callable[ - [gcn_address_group.AddAddressGroupItemsRequest], - Awaitable[operations_pb2.Operation]]: + def add_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation], + ]: r"""Return a callable for the add address group items method over gRPC. Adds items to an address group. @@ -461,18 +490,21 @@ def add_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'add_address_group_items' not in self._stubs: - self._stubs['add_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/AddAddressGroupItems', + if "add_address_group_items" not in self._stubs: + self._stubs["add_address_group_items"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/AddAddressGroupItems", request_serializer=gcn_address_group.AddAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['add_address_group_items'] + return self._stubs["add_address_group_items"] @property - def remove_address_group_items(self) -> Callable[ - [gcn_address_group.RemoveAddressGroupItemsRequest], - Awaitable[operations_pb2.Operation]]: + def remove_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation], + ]: r"""Return a callable for the remove address group items method over gRPC. Removes items from an address group. @@ -487,18 +519,23 @@ def remove_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'remove_address_group_items' not in self._stubs: - self._stubs['remove_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/RemoveAddressGroupItems', + if "remove_address_group_items" not in self._stubs: + self._stubs[ + "remove_address_group_items" + ] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/RemoveAddressGroupItems", request_serializer=gcn_address_group.RemoveAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['remove_address_group_items'] + return self._stubs["remove_address_group_items"] @property - def clone_address_group_items(self) -> Callable[ - [gcn_address_group.CloneAddressGroupItemsRequest], - Awaitable[operations_pb2.Operation]]: + def clone_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], + Awaitable[operations_pb2.Operation], + ]: r"""Return a callable for the clone address group items method over gRPC. Clones items from one address group to another. @@ -513,18 +550,20 @@ def clone_address_group_items(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'clone_address_group_items' not in self._stubs: - self._stubs['clone_address_group_items'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CloneAddressGroupItems', + if "clone_address_group_items" not in self._stubs: + self._stubs["clone_address_group_items"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/CloneAddressGroupItems", request_serializer=gcn_address_group.CloneAddressGroupItemsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['clone_address_group_items'] + return self._stubs["clone_address_group_items"] @property - def delete_address_group(self) -> Callable[ - [address_group.DeleteAddressGroupRequest], - Awaitable[operations_pb2.Operation]]: + def delete_address_group( + self, + ) -> Callable[ + [address_group.DeleteAddressGroupRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete address group method over gRPC. Deletes an address group. @@ -539,18 +578,21 @@ def delete_address_group(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_address_group' not in self._stubs: - self._stubs['delete_address_group'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/DeleteAddressGroup', + if "delete_address_group" not in self._stubs: + self._stubs["delete_address_group"] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/DeleteAddressGroup", request_serializer=address_group.DeleteAddressGroupRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_address_group'] + return self._stubs["delete_address_group"] @property - def list_address_group_references(self) -> Callable[ - [gcn_address_group.ListAddressGroupReferencesRequest], - Awaitable[gcn_address_group.ListAddressGroupReferencesResponse]]: + def list_address_group_references( + self, + ) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + Awaitable[gcn_address_group.ListAddressGroupReferencesResponse], + ]: r"""Return a callable for the list address group references method over gRPC. Lists references of an address group. @@ -565,16 +607,18 @@ def list_address_group_references(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_address_group_references' not in self._stubs: - self._stubs['list_address_group_references'] = self._logged_channel.unary_unary( - '/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroupReferences', + if "list_address_group_references" not in self._stubs: + self._stubs[ + "list_address_group_references" + ] = self._logged_channel.unary_unary( + "/google.cloud.networksecurity.v1.OrganizationAddressGroupService/ListAddressGroupReferences", request_serializer=gcn_address_group.ListAddressGroupReferencesRequest.serialize, response_deserializer=gcn_address_group.ListAddressGroupReferencesResponse.deserialize, ) - return self._stubs['list_address_group_references'] + return self._stubs["list_address_group_references"] def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { self.list_address_groups: self._wrap_method( self.list_address_groups, @@ -684,8 +728,7 @@ def kind(self) -> str: def delete_operation( self, ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ + r"""Return a callable for the delete_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -702,8 +745,7 @@ def delete_operation( def cancel_operation( self, ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ + r"""Return a callable for the cancel_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -720,8 +762,7 @@ def cancel_operation( def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + r"""Return a callable for the get_operation method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -737,9 +778,10 @@ def get_operation( @property def list_operations( self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -755,9 +797,10 @@ def list_operations( @property def list_locations( self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -774,8 +817,7 @@ def list_locations( def get_location( self, ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ + r"""Return a callable for the list locations method over gRPC.""" # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need @@ -843,7 +885,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. Tests the specified permissions against the IAM access control @@ -868,6 +911,4 @@ def test_iam_permissions( return self._stubs["test_iam_permissions"] -__all__ = ( - 'OrganizationAddressGroupServiceGrpcAsyncIOTransport', -) +__all__ = ("OrganizationAddressGroupServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py similarity index 65% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py index 2dc3bcb3a05e..6f633df06d39 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest.py @@ -13,37 +13,30 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import logging +import dataclasses import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 -import google.protobuf - -from google.protobuf import json_format -from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +import google.protobuf +from google.protobuf import json_format from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -from google.cloud.network_security_v1.types import address_group from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.longrunning import operations_pb2 # type: ignore - +from google.cloud.network_security_v1.types import address_group -from .rest_base import _BaseOrganizationAddressGroupServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseOrganizationAddressGroupServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -52,6 +45,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -160,7 +154,15 @@ def post_update_address_group(self, response): """ - def pre_add_address_group_items(self, request: gcn_address_group.AddAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.AddAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_add_address_group_items( + self, + request: gcn_address_group.AddAddressGroupItemsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.AddAddressGroupItemsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for add_address_group_items Override in a subclass to manipulate the request or metadata @@ -168,7 +170,9 @@ def pre_add_address_group_items(self, request: gcn_address_group.AddAddressGroup """ return request, metadata - def post_add_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_add_address_group_items( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for add_address_group_items DEPRECATED. Please use the `post_add_address_group_items_with_metadata` @@ -181,7 +185,11 @@ def post_add_address_group_items(self, response: operations_pb2.Operation) -> op """ return response - def post_add_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_add_address_group_items_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for add_address_group_items Override in a subclass to read or manipulate the response or metadata after it @@ -196,7 +204,14 @@ def post_add_address_group_items_with_metadata(self, response: operations_pb2.Op """ return response, metadata - def pre_clone_address_group_items(self, request: gcn_address_group.CloneAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.CloneAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_clone_address_group_items( + self, + request: gcn_address_group.CloneAddressGroupItemsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.CloneAddressGroupItemsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for clone_address_group_items Override in a subclass to manipulate the request or metadata @@ -204,7 +219,9 @@ def pre_clone_address_group_items(self, request: gcn_address_group.CloneAddressG """ return request, metadata - def post_clone_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_clone_address_group_items( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for clone_address_group_items DEPRECATED. Please use the `post_clone_address_group_items_with_metadata` @@ -217,7 +234,11 @@ def post_clone_address_group_items(self, response: operations_pb2.Operation) -> """ return response - def post_clone_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_clone_address_group_items_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for clone_address_group_items Override in a subclass to read or manipulate the response or metadata after it @@ -232,7 +253,14 @@ def post_clone_address_group_items_with_metadata(self, response: operations_pb2. """ return response, metadata - def pre_create_address_group(self, request: gcn_address_group.CreateAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.CreateAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_create_address_group( + self, + request: gcn_address_group.CreateAddressGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.CreateAddressGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_address_group Override in a subclass to manipulate the request or metadata @@ -240,7 +268,9 @@ def pre_create_address_group(self, request: gcn_address_group.CreateAddressGroup """ return request, metadata - def post_create_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_address_group( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_address_group DEPRECATED. Please use the `post_create_address_group_with_metadata` @@ -253,7 +283,11 @@ def post_create_address_group(self, response: operations_pb2.Operation) -> opera """ return response - def post_create_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_address_group_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_address_group Override in a subclass to read or manipulate the response or metadata after it @@ -268,7 +302,13 @@ def post_create_address_group_with_metadata(self, response: operations_pb2.Opera """ return response, metadata - def pre_delete_address_group(self, request: address_group.DeleteAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.DeleteAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_address_group( + self, + request: address_group.DeleteAddressGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + address_group.DeleteAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_address_group Override in a subclass to manipulate the request or metadata @@ -276,7 +316,9 @@ def pre_delete_address_group(self, request: address_group.DeleteAddressGroupRequ """ return request, metadata - def post_delete_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_address_group( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_address_group DEPRECATED. Please use the `post_delete_address_group_with_metadata` @@ -289,7 +331,11 @@ def post_delete_address_group(self, response: operations_pb2.Operation) -> opera """ return response - def post_delete_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_delete_address_group_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for delete_address_group Override in a subclass to read or manipulate the response or metadata after it @@ -304,7 +350,13 @@ def post_delete_address_group_with_metadata(self, response: operations_pb2.Opera """ return response, metadata - def pre_get_address_group(self, request: address_group.GetAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.GetAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_address_group( + self, + request: address_group.GetAddressGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + address_group.GetAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_address_group Override in a subclass to manipulate the request or metadata @@ -312,7 +364,9 @@ def pre_get_address_group(self, request: address_group.GetAddressGroupRequest, m """ return request, metadata - def post_get_address_group(self, response: address_group.AddressGroup) -> address_group.AddressGroup: + def post_get_address_group( + self, response: address_group.AddressGroup + ) -> address_group.AddressGroup: """Post-rpc interceptor for get_address_group DEPRECATED. Please use the `post_get_address_group_with_metadata` @@ -325,7 +379,11 @@ def post_get_address_group(self, response: address_group.AddressGroup) -> addres """ return response - def post_get_address_group_with_metadata(self, response: address_group.AddressGroup, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.AddressGroup, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_address_group_with_metadata( + self, + response: address_group.AddressGroup, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[address_group.AddressGroup, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_address_group Override in a subclass to read or manipulate the response or metadata after it @@ -340,7 +398,14 @@ def post_get_address_group_with_metadata(self, response: address_group.AddressGr """ return response, metadata - def pre_list_address_group_references(self, request: gcn_address_group.ListAddressGroupReferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.ListAddressGroupReferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_address_group_references( + self, + request: gcn_address_group.ListAddressGroupReferencesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.ListAddressGroupReferencesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_address_group_references Override in a subclass to manipulate the request or metadata @@ -348,7 +413,9 @@ def pre_list_address_group_references(self, request: gcn_address_group.ListAddre """ return request, metadata - def post_list_address_group_references(self, response: gcn_address_group.ListAddressGroupReferencesResponse) -> gcn_address_group.ListAddressGroupReferencesResponse: + def post_list_address_group_references( + self, response: gcn_address_group.ListAddressGroupReferencesResponse + ) -> gcn_address_group.ListAddressGroupReferencesResponse: """Post-rpc interceptor for list_address_group_references DEPRECATED. Please use the `post_list_address_group_references_with_metadata` @@ -361,7 +428,14 @@ def post_list_address_group_references(self, response: gcn_address_group.ListAdd """ return response - def post_list_address_group_references_with_metadata(self, response: gcn_address_group.ListAddressGroupReferencesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.ListAddressGroupReferencesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_address_group_references_with_metadata( + self, + response: gcn_address_group.ListAddressGroupReferencesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.ListAddressGroupReferencesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_address_group_references Override in a subclass to read or manipulate the response or metadata after it @@ -376,7 +450,13 @@ def post_list_address_group_references_with_metadata(self, response: gcn_address """ return response, metadata - def pre_list_address_groups(self, request: address_group.ListAddressGroupsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.ListAddressGroupsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_address_groups( + self, + request: address_group.ListAddressGroupsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + address_group.ListAddressGroupsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_address_groups Override in a subclass to manipulate the request or metadata @@ -384,7 +464,9 @@ def pre_list_address_groups(self, request: address_group.ListAddressGroupsReques """ return request, metadata - def post_list_address_groups(self, response: address_group.ListAddressGroupsResponse) -> address_group.ListAddressGroupsResponse: + def post_list_address_groups( + self, response: address_group.ListAddressGroupsResponse + ) -> address_group.ListAddressGroupsResponse: """Post-rpc interceptor for list_address_groups DEPRECATED. Please use the `post_list_address_groups_with_metadata` @@ -397,7 +479,13 @@ def post_list_address_groups(self, response: address_group.ListAddressGroupsResp """ return response - def post_list_address_groups_with_metadata(self, response: address_group.ListAddressGroupsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[address_group.ListAddressGroupsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_address_groups_with_metadata( + self, + response: address_group.ListAddressGroupsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + address_group.ListAddressGroupsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_address_groups Override in a subclass to read or manipulate the response or metadata after it @@ -412,7 +500,14 @@ def post_list_address_groups_with_metadata(self, response: address_group.ListAdd """ return response, metadata - def pre_remove_address_group_items(self, request: gcn_address_group.RemoveAddressGroupItemsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.RemoveAddressGroupItemsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_remove_address_group_items( + self, + request: gcn_address_group.RemoveAddressGroupItemsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.RemoveAddressGroupItemsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for remove_address_group_items Override in a subclass to manipulate the request or metadata @@ -420,7 +515,9 @@ def pre_remove_address_group_items(self, request: gcn_address_group.RemoveAddres """ return request, metadata - def post_remove_address_group_items(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_remove_address_group_items( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for remove_address_group_items DEPRECATED. Please use the `post_remove_address_group_items_with_metadata` @@ -433,7 +530,11 @@ def post_remove_address_group_items(self, response: operations_pb2.Operation) -> """ return response - def post_remove_address_group_items_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_remove_address_group_items_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for remove_address_group_items Override in a subclass to read or manipulate the response or metadata after it @@ -448,7 +549,14 @@ def post_remove_address_group_items_with_metadata(self, response: operations_pb2 """ return response, metadata - def pre_update_address_group(self, request: gcn_address_group.UpdateAddressGroupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gcn_address_group.UpdateAddressGroupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_address_group( + self, + request: gcn_address_group.UpdateAddressGroupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcn_address_group.UpdateAddressGroupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_address_group Override in a subclass to manipulate the request or metadata @@ -456,7 +564,9 @@ def pre_update_address_group(self, request: gcn_address_group.UpdateAddressGroup """ return request, metadata - def post_update_address_group(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_update_address_group( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for update_address_group DEPRECATED. Please use the `post_update_address_group_with_metadata` @@ -469,7 +579,11 @@ def post_update_address_group(self, response: operations_pb2.Operation) -> opera """ return response - def post_update_address_group_with_metadata(self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_address_group_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_address_group Override in a subclass to read or manipulate the response or metadata after it @@ -485,8 +599,12 @@ def post_update_address_group_with_metadata(self, response: operations_pb2.Opera return response, metadata def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -506,8 +624,12 @@ def post_get_location( return response def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -527,8 +649,12 @@ def post_list_locations( return response def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_iam_policy Override in a subclass to manipulate the request or metadata @@ -536,9 +662,7 @@ def pre_get_iam_policy( """ return request, metadata - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for get_iam_policy Override in a subclass to manipulate the response @@ -548,8 +672,12 @@ def post_get_iam_policy( return response def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for set_iam_policy Override in a subclass to manipulate the request or metadata @@ -557,9 +685,7 @@ def pre_set_iam_policy( """ return request, metadata - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for set_iam_policy Override in a subclass to manipulate the response @@ -569,8 +695,13 @@ def post_set_iam_policy( return response def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for test_iam_permissions Override in a subclass to manipulate the request or metadata @@ -590,8 +721,12 @@ def post_test_iam_permissions( return response def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -599,9 +734,7 @@ def pre_cancel_operation( """ return request, metadata - def post_cancel_operation( - self, response: None - ) -> None: + def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -611,8 +744,12 @@ def post_cancel_operation( return response def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -620,9 +757,7 @@ def pre_delete_operation( """ return request, metadata - def post_delete_operation( - self, response: None - ) -> None: + def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -632,8 +767,12 @@ def post_delete_operation( return response def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -653,8 +792,12 @@ def post_get_operation( return response def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -681,7 +824,9 @@ class OrganizationAddressGroupServiceRestStub: _interceptor: OrganizationAddressGroupServiceRestInterceptor -class OrganizationAddressGroupServiceRestTransport(_BaseOrganizationAddressGroupServiceRestTransport): +class OrganizationAddressGroupServiceRestTransport( + _BaseOrganizationAddressGroupServiceRestTransport +): """REST backend synchronous transport for OrganizationAddressGroupService. Organization AddressGroup is created under organization. @@ -695,20 +840,21 @@ class OrganizationAddressGroupServiceRestTransport(_BaseOrganizationAddressGroup It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[OrganizationAddressGroupServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "networksecurity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[OrganizationAddressGroupServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -751,14 +897,17 @@ def __init__(self, *, client_info=client_info, always_use_jwt_access=always_use_jwt_access, url_scheme=url_scheme, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or OrganizationAddressGroupServiceRestInterceptor() + self._interceptor = ( + interceptor or OrganizationAddressGroupServiceRestInterceptor() + ) self._prep_wrapped_messages(client_info) @property @@ -771,66 +920,74 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ + "google.longrunning.Operations.CancelOperation": [ { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", }, { - 'method': 'post', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', - 'body': '*', + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}:cancel", + "body": "*", }, ], - 'google.longrunning.Operations.DeleteOperation': [ + "google.longrunning.Operations.DeleteOperation": [ { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, { - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", }, ], - 'google.longrunning.Operations.ListOperations': [ + "google.longrunning.Operations.ListOperations": [ { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", }, { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}/operations', + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}/operations", }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client - class _AddAddressGroupItems(_BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems, OrganizationAddressGroupServiceRestStub): + class _AddAddressGroupItems( + _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): - return hash("OrganizationAddressGroupServiceRestTransport.AddAddressGroupItems") + return hash( + "OrganizationAddressGroupServiceRestTransport.AddAddressGroupItems" + ) @staticmethod def _get_response( @@ -840,27 +997,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: gcn_address_group.AddAddressGroupItemsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: gcn_address_group.AddAddressGroupItemsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the add address group items method over HTTP. Args: @@ -883,32 +1042,46 @@ def __call__(self, """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_http_options() + ) - request, metadata = self._interceptor.pre_add_address_group_items(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_add_address_group_items( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_transcoded_request( + http_options, request + ) - body = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_request_body_json(transcoded_request) + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.AddAddressGroupItems", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "AddAddressGroupItems", "httpRequest": http_request, @@ -917,7 +1090,15 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._AddAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OrganizationAddressGroupServiceRestTransport._AddAddressGroupItems._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -930,20 +1111,24 @@ def __call__(self, resp = self._interceptor.post_add_address_group_items(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_add_address_group_items_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_add_address_group_items_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.add_address_group_items", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "AddAddressGroupItems", "metadata": http_response["headers"], @@ -952,9 +1137,14 @@ def __call__(self, ) return resp - class _CloneAddressGroupItems(_BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems, OrganizationAddressGroupServiceRestStub): + class _CloneAddressGroupItems( + _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): - return hash("OrganizationAddressGroupServiceRestTransport.CloneAddressGroupItems") + return hash( + "OrganizationAddressGroupServiceRestTransport.CloneAddressGroupItems" + ) @staticmethod def _get_response( @@ -964,27 +1154,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: gcn_address_group.CloneAddressGroupItemsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: gcn_address_group.CloneAddressGroupItemsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the clone address group items method over HTTP. Args: @@ -1007,32 +1199,46 @@ def __call__(self, """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_http_options() + ) - request, metadata = self._interceptor.pre_clone_address_group_items(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_clone_address_group_items( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_transcoded_request( + http_options, request + ) - body = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_request_body_json(transcoded_request) + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.CloneAddressGroupItems", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "CloneAddressGroupItems", "httpRequest": http_request, @@ -1041,7 +1247,15 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._CloneAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OrganizationAddressGroupServiceRestTransport._CloneAddressGroupItems._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1054,20 +1268,24 @@ def __call__(self, resp = self._interceptor.post_clone_address_group_items(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_clone_address_group_items_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_clone_address_group_items_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.clone_address_group_items", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "CloneAddressGroupItems", "metadata": http_response["headers"], @@ -1076,9 +1294,14 @@ def __call__(self, ) return resp - class _CreateAddressGroup(_BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup, OrganizationAddressGroupServiceRestStub): + class _CreateAddressGroup( + _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): - return hash("OrganizationAddressGroupServiceRestTransport.CreateAddressGroup") + return hash( + "OrganizationAddressGroupServiceRestTransport.CreateAddressGroup" + ) @staticmethod def _get_response( @@ -1088,27 +1311,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: gcn_address_group.CreateAddressGroupRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: gcn_address_group.CreateAddressGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the create address group method over HTTP. Args: @@ -1131,32 +1356,46 @@ def __call__(self, """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_http_options() + ) - request, metadata = self._interceptor.pre_create_address_group(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_address_group( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_transcoded_request( + http_options, request + ) - body = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_request_body_json(transcoded_request) + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.CreateAddressGroup", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "CreateAddressGroup", "httpRequest": http_request, @@ -1165,7 +1404,15 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._CreateAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OrganizationAddressGroupServiceRestTransport._CreateAddressGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1178,20 +1425,24 @@ def __call__(self, resp = self._interceptor.post_create_address_group(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_address_group_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_address_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.create_address_group", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "CreateAddressGroup", "metadata": http_response["headers"], @@ -1200,9 +1451,14 @@ def __call__(self, ) return resp - class _DeleteAddressGroup(_BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup, OrganizationAddressGroupServiceRestStub): + class _DeleteAddressGroup( + _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): - return hash("OrganizationAddressGroupServiceRestTransport.DeleteAddressGroup") + return hash( + "OrganizationAddressGroupServiceRestTransport.DeleteAddressGroup" + ) @staticmethod def _get_response( @@ -1212,26 +1468,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: address_group.DeleteAddressGroupRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: address_group.DeleteAddressGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the delete address group method over HTTP. Args: @@ -1254,30 +1512,42 @@ def __call__(self, """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_address_group(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_address_group( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.DeleteAddressGroup", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "DeleteAddressGroup", "httpRequest": http_request, @@ -1286,7 +1556,14 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._DeleteAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OrganizationAddressGroupServiceRestTransport._DeleteAddressGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1299,20 +1576,24 @@ def __call__(self, resp = self._interceptor.post_delete_address_group(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_address_group_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_delete_address_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.delete_address_group", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "DeleteAddressGroup", "metadata": http_response["headers"], @@ -1321,7 +1602,10 @@ def __call__(self, ) return resp - class _GetAddressGroup(_BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup, OrganizationAddressGroupServiceRestStub): + class _GetAddressGroup( + _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): return hash("OrganizationAddressGroupServiceRestTransport.GetAddressGroup") @@ -1333,26 +1617,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: address_group.GetAddressGroupRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> address_group.AddressGroup: + def __call__( + self, + request: address_group.GetAddressGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.AddressGroup: r"""Call the get address group method over HTTP. Args: @@ -1375,30 +1661,42 @@ def __call__(self, """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_http_options() + ) - request, metadata = self._interceptor.pre_get_address_group(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_address_group( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.GetAddressGroup", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "GetAddressGroup", "httpRequest": http_request, @@ -1407,7 +1705,14 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._GetAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OrganizationAddressGroupServiceRestTransport._GetAddressGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1422,20 +1727,24 @@ def __call__(self, resp = self._interceptor.post_get_address_group(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_address_group_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_address_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = address_group.AddressGroup.to_json(response) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.get_address_group", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "GetAddressGroup", "metadata": http_response["headers"], @@ -1444,9 +1753,14 @@ def __call__(self, ) return resp - class _ListAddressGroupReferences(_BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences, OrganizationAddressGroupServiceRestStub): + class _ListAddressGroupReferences( + _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): - return hash("OrganizationAddressGroupServiceRestTransport.ListAddressGroupReferences") + return hash( + "OrganizationAddressGroupServiceRestTransport.ListAddressGroupReferences" + ) @staticmethod def _get_response( @@ -1456,72 +1770,86 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: gcn_address_group.ListAddressGroupReferencesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gcn_address_group.ListAddressGroupReferencesResponse: + def __call__( + self, + request: gcn_address_group.ListAddressGroupReferencesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcn_address_group.ListAddressGroupReferencesResponse: r"""Call the list address group - references method over HTTP. - - Args: - request (~.gcn_address_group.ListAddressGroupReferencesRequest): - The request object. Request used by the - ListAddressGroupReferences method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.gcn_address_group.ListAddressGroupReferencesResponse: - Response of the - ListAddressGroupReferences method. + references method over HTTP. + + Args: + request (~.gcn_address_group.ListAddressGroupReferencesRequest): + The request object. Request used by the + ListAddressGroupReferences method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcn_address_group.ListAddressGroupReferencesResponse: + Response of the + ListAddressGroupReferences method. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_http_options() + ) - request, metadata = self._interceptor.pre_list_address_group_references(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_address_group_references( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.ListAddressGroupReferences", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "ListAddressGroupReferences", "httpRequest": http_request, @@ -1530,7 +1858,14 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._ListAddressGroupReferences._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OrganizationAddressGroupServiceRestTransport._ListAddressGroupReferences._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1545,20 +1880,31 @@ def __call__(self, resp = self._interceptor.post_list_address_group_references(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_address_group_references_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_list_address_group_references_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = gcn_address_group.ListAddressGroupReferencesResponse.to_json(response) + response_payload = ( + gcn_address_group.ListAddressGroupReferencesResponse.to_json( + response + ) + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.list_address_group_references", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "ListAddressGroupReferences", "metadata": http_response["headers"], @@ -1567,9 +1913,14 @@ def __call__(self, ) return resp - class _ListAddressGroups(_BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups, OrganizationAddressGroupServiceRestStub): + class _ListAddressGroups( + _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): - return hash("OrganizationAddressGroupServiceRestTransport.ListAddressGroups") + return hash( + "OrganizationAddressGroupServiceRestTransport.ListAddressGroups" + ) @staticmethod def _get_response( @@ -1579,26 +1930,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: address_group.ListAddressGroupsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> address_group.ListAddressGroupsResponse: + def __call__( + self, + request: address_group.ListAddressGroupsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> address_group.ListAddressGroupsResponse: r"""Call the list address groups method over HTTP. Args: @@ -1620,30 +1973,42 @@ def __call__(self, """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_http_options() + ) - request, metadata = self._interceptor.pre_list_address_groups(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_address_groups( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.ListAddressGroups", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "ListAddressGroups", "httpRequest": http_request, @@ -1652,7 +2017,14 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._ListAddressGroups._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OrganizationAddressGroupServiceRestTransport._ListAddressGroups._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1667,20 +2039,26 @@ def __call__(self, resp = self._interceptor.post_list_address_groups(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_address_groups_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_address_groups_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = address_group.ListAddressGroupsResponse.to_json(response) + response_payload = address_group.ListAddressGroupsResponse.to_json( + response + ) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.list_address_groups", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "ListAddressGroups", "metadata": http_response["headers"], @@ -1689,9 +2067,14 @@ def __call__(self, ) return resp - class _RemoveAddressGroupItems(_BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems, OrganizationAddressGroupServiceRestStub): + class _RemoveAddressGroupItems( + _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): - return hash("OrganizationAddressGroupServiceRestTransport.RemoveAddressGroupItems") + return hash( + "OrganizationAddressGroupServiceRestTransport.RemoveAddressGroupItems" + ) @staticmethod def _get_response( @@ -1701,76 +2084,92 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: gcn_address_group.RemoveAddressGroupItemsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: gcn_address_group.RemoveAddressGroupItemsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the remove address group - items method over HTTP. - - Args: - request (~.gcn_address_group.RemoveAddressGroupItemsRequest): - The request object. Request used by the - RemoveAddressGroupItems method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + items method over HTTP. + + Args: + request (~.gcn_address_group.RemoveAddressGroupItemsRequest): + The request object. Request used by the + RemoveAddressGroupItems method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_http_options() + ) - request, metadata = self._interceptor.pre_remove_address_group_items(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_remove_address_group_items( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_transcoded_request( + http_options, request + ) - body = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_request_body_json(transcoded_request) + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.RemoveAddressGroupItems", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "RemoveAddressGroupItems", "httpRequest": http_request, @@ -1779,7 +2178,15 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._RemoveAddressGroupItems._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OrganizationAddressGroupServiceRestTransport._RemoveAddressGroupItems._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1792,20 +2199,24 @@ def __call__(self, resp = self._interceptor.post_remove_address_group_items(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_remove_address_group_items_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_remove_address_group_items_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.remove_address_group_items", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "RemoveAddressGroupItems", "metadata": http_response["headers"], @@ -1814,9 +2225,14 @@ def __call__(self, ) return resp - class _UpdateAddressGroup(_BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup, OrganizationAddressGroupServiceRestStub): + class _UpdateAddressGroup( + _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): - return hash("OrganizationAddressGroupServiceRestTransport.UpdateAddressGroup") + return hash( + "OrganizationAddressGroupServiceRestTransport.UpdateAddressGroup" + ) @staticmethod def _get_response( @@ -1826,27 +2242,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: gcn_address_group.UpdateAddressGroupRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: + def __call__( + self, + request: gcn_address_group.UpdateAddressGroupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the update address group method over HTTP. Args: @@ -1869,32 +2287,46 @@ def __call__(self, """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_http_options() + ) - request, metadata = self._interceptor.pre_update_address_group(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_address_group( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_transcoded_request( + http_options, request + ) - body = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_request_body_json(transcoded_request) + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.UpdateAddressGroup", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "UpdateAddressGroup", "httpRequest": http_request, @@ -1903,7 +2335,15 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._UpdateAddressGroup._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OrganizationAddressGroupServiceRestTransport._UpdateAddressGroup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1916,20 +2356,24 @@ def __call__(self, resp = self._interceptor.post_update_address_group(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_address_group_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_address_group_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.update_address_group", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "UpdateAddressGroup", "metadata": http_response["headers"], @@ -1939,82 +2383,101 @@ def __call__(self, return resp @property - def add_address_group_items(self) -> Callable[ - [gcn_address_group.AddAddressGroupItemsRequest], - operations_pb2.Operation]: + def add_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.AddAddressGroupItemsRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._AddAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + return self._AddAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore @property - def clone_address_group_items(self) -> Callable[ - [gcn_address_group.CloneAddressGroupItemsRequest], - operations_pb2.Operation]: + def clone_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.CloneAddressGroupItemsRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CloneAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + return self._CloneAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore @property - def create_address_group(self) -> Callable[ - [gcn_address_group.CreateAddressGroupRequest], - operations_pb2.Operation]: + def create_address_group( + self, + ) -> Callable[ + [gcn_address_group.CreateAddressGroupRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._CreateAddressGroup(self._session, self._host, self._interceptor) # type: ignore + return self._CreateAddressGroup(self._session, self._host, self._interceptor) # type: ignore @property - def delete_address_group(self) -> Callable[ - [address_group.DeleteAddressGroupRequest], - operations_pb2.Operation]: + def delete_address_group( + self, + ) -> Callable[[address_group.DeleteAddressGroupRequest], operations_pb2.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._DeleteAddressGroup(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteAddressGroup(self._session, self._host, self._interceptor) # type: ignore @property - def get_address_group(self) -> Callable[ - [address_group.GetAddressGroupRequest], - address_group.AddressGroup]: + def get_address_group( + self, + ) -> Callable[[address_group.GetAddressGroupRequest], address_group.AddressGroup]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetAddressGroup(self._session, self._host, self._interceptor) # type: ignore + return self._GetAddressGroup(self._session, self._host, self._interceptor) # type: ignore @property - def list_address_group_references(self) -> Callable[ - [gcn_address_group.ListAddressGroupReferencesRequest], - gcn_address_group.ListAddressGroupReferencesResponse]: + def list_address_group_references( + self, + ) -> Callable[ + [gcn_address_group.ListAddressGroupReferencesRequest], + gcn_address_group.ListAddressGroupReferencesResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListAddressGroupReferences(self._session, self._host, self._interceptor) # type: ignore + return self._ListAddressGroupReferences(self._session, self._host, self._interceptor) # type: ignore @property - def list_address_groups(self) -> Callable[ - [address_group.ListAddressGroupsRequest], - address_group.ListAddressGroupsResponse]: + def list_address_groups( + self, + ) -> Callable[ + [address_group.ListAddressGroupsRequest], + address_group.ListAddressGroupsResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListAddressGroups(self._session, self._host, self._interceptor) # type: ignore + return self._ListAddressGroups(self._session, self._host, self._interceptor) # type: ignore @property - def remove_address_group_items(self) -> Callable[ - [gcn_address_group.RemoveAddressGroupItemsRequest], - operations_pb2.Operation]: + def remove_address_group_items( + self, + ) -> Callable[ + [gcn_address_group.RemoveAddressGroupItemsRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._RemoveAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore + return self._RemoveAddressGroupItems(self._session, self._host, self._interceptor) # type: ignore @property - def update_address_group(self) -> Callable[ - [gcn_address_group.UpdateAddressGroupRequest], - operations_pb2.Operation]: + def update_address_group( + self, + ) -> Callable[ + [gcn_address_group.UpdateAddressGroupRequest], operations_pb2.Operation + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateAddressGroup(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateAddressGroup(self._session, self._host, self._interceptor) # type: ignore @property def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - class _GetLocation(_BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation, OrganizationAddressGroupServiceRestStub): + class _GetLocation( + _BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): return hash("OrganizationAddressGroupServiceRestTransport.GetLocation") @@ -2026,27 +2489,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.Location: - + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: r"""Call the get location method over HTTP. Args: @@ -2064,30 +2528,40 @@ def __call__(self, locations_pb2.Location: Response from GetLocation method. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation._get_http_options() + ) request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "GetLocation", "httpRequest": http_request, @@ -2096,7 +2570,16 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + OrganizationAddressGroupServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2107,19 +2590,21 @@ def __call__(self, resp = locations_pb2.Location() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_location(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.GetLocation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "GetLocation", "httpResponse": http_response, @@ -2130,9 +2615,12 @@ def __call__(self, @property def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - class _ListLocations(_BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations, OrganizationAddressGroupServiceRestStub): + class _ListLocations( + _BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): return hash("OrganizationAddressGroupServiceRestTransport.ListLocations") @@ -2144,27 +2632,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> locations_pb2.ListLocationsResponse: - + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: r"""Call the list locations method over HTTP. Args: @@ -2182,30 +2671,40 @@ def __call__(self, locations_pb2.ListLocationsResponse: Response from ListLocations method. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations._get_http_options() + ) request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "ListLocations", "httpRequest": http_request, @@ -2214,7 +2713,14 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OrganizationAddressGroupServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2225,19 +2731,21 @@ def __call__(self, resp = locations_pb2.ListLocationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_locations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.ListLocations", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "ListLocations", "httpResponse": http_response, @@ -2248,9 +2756,12 @@ def __call__(self, @property def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - class _GetIamPolicy(_BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy, OrganizationAddressGroupServiceRestStub): + class _GetIamPolicy( + _BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): return hash("OrganizationAddressGroupServiceRestTransport.GetIamPolicy") @@ -2262,27 +2773,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: r"""Call the get iam policy method over HTTP. Args: @@ -2300,30 +2812,40 @@ def __call__(self, policy_pb2.Policy: Response from GetIamPolicy method. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.GetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "GetIamPolicy", "httpRequest": http_request, @@ -2332,7 +2854,14 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OrganizationAddressGroupServiceRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2343,19 +2872,21 @@ def __call__(self, resp = policy_pb2.Policy() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.GetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "GetIamPolicy", "httpResponse": http_response, @@ -2366,9 +2897,12 @@ def __call__(self, @property def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - class _SetIamPolicy(_BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy, OrganizationAddressGroupServiceRestStub): + class _SetIamPolicy( + _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): return hash("OrganizationAddressGroupServiceRestTransport.SetIamPolicy") @@ -2380,28 +2914,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: r"""Call the set iam policy method over HTTP. Args: @@ -2419,32 +2954,44 @@ def __call__(self, policy_pb2.Policy: Response from SetIamPolicy method. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_http_options() + ) request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) - body = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.SetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "SetIamPolicy", "httpRequest": http_request, @@ -2453,7 +3000,15 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OrganizationAddressGroupServiceRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2464,19 +3019,21 @@ def __call__(self, resp = policy_pb2.Policy() resp = json_format.Parse(content, resp) resp = self._interceptor.post_set_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.SetIamPolicy", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "SetIamPolicy", "httpResponse": http_response, @@ -2487,11 +3044,16 @@ def __call__(self, @property def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - class _TestIamPermissions(_BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions, OrganizationAddressGroupServiceRestStub): + class _TestIamPermissions( + _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): - return hash("OrganizationAddressGroupServiceRestTransport.TestIamPermissions") + return hash( + "OrganizationAddressGroupServiceRestTransport.TestIamPermissions" + ) @staticmethod def _get_response( @@ -2501,28 +3063,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Call the test iam permissions method over HTTP. Args: @@ -2540,32 +3103,46 @@ def __call__(self, iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_http_options() + ) - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) - body = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.TestIamPermissions", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "TestIamPermissions", "httpRequest": http_request, @@ -2574,7 +3151,15 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OrganizationAddressGroupServiceRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2585,19 +3170,21 @@ def __call__(self, resp = iam_policy_pb2.TestIamPermissionsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_test_iam_permissions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.TestIamPermissions", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "TestIamPermissions", "httpResponse": http_response, @@ -2608,9 +3195,12 @@ def __call__(self, @property def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - class _CancelOperation(_BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation, OrganizationAddressGroupServiceRestStub): + class _CancelOperation( + _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): return hash("OrganizationAddressGroupServiceRestTransport.CancelOperation") @@ -2622,28 +3212,29 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the cancel operation method over HTTP. Args: @@ -2658,32 +3249,46 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) - body = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + body = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.CancelOperation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "CancelOperation", "httpRequest": http_request, @@ -2692,7 +3297,15 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OrganizationAddressGroupServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2703,9 +3316,12 @@ def __call__(self, @property def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - class _DeleteOperation(_BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation, OrganizationAddressGroupServiceRestStub): + class _DeleteOperation( + _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): return hash("OrganizationAddressGroupServiceRestTransport.DeleteOperation") @@ -2717,27 +3333,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> None: - + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Call the delete operation method over HTTP. Args: @@ -2752,30 +3369,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.DeleteOperation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "DeleteOperation", "httpRequest": http_request, @@ -2784,7 +3413,14 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OrganizationAddressGroupServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2795,9 +3431,12 @@ def __call__(self, @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - class _GetOperation(_BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation, OrganizationAddressGroupServiceRestStub): + class _GetOperation( + _BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): return hash("OrganizationAddressGroupServiceRestTransport.GetOperation") @@ -2809,27 +3448,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -2847,30 +3487,40 @@ def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation._get_http_options() + ) request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "GetOperation", "httpRequest": http_request, @@ -2879,7 +3529,14 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OrganizationAddressGroupServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -2890,19 +3547,21 @@ def __call__(self, resp = operations_pb2.Operation() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_operation(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.GetOperation", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "GetOperation", "httpResponse": http_response, @@ -2913,9 +3572,12 @@ def __call__(self, @property def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - class _ListOperations(_BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations, OrganizationAddressGroupServiceRestStub): + class _ListOperations( + _BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations, + OrganizationAddressGroupServiceRestStub, + ): def __hash__(self): return hash("OrganizationAddressGroupServiceRestTransport.ListOperations") @@ -2927,27 +3589,28 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) return response - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. Args: @@ -2965,30 +3628,40 @@ def __call__(self, operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options = _BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations._get_http_options() + http_options = ( + _BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations._get_http_options() + ) request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + transcoded_request = _BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + query_params = _BaseOrganizationAddressGroupServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = json_format.MessageToJson(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "ListOperations", "httpRequest": http_request, @@ -2997,7 +3670,14 @@ def __call__(self, ) # Send the request - response = OrganizationAddressGroupServiceRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OrganizationAddressGroupServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -3008,19 +3688,21 @@ def __call__(self, resp = operations_pb2.ListOperationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { "payload": response_payload, - "headers": dict(response.headers), + "headers": dict(response.headers), "status": response.status_code, } _LOGGER.debug( "Received response for google.cloud.networksecurity_v1.OrganizationAddressGroupServiceAsyncClient.ListOperations", - extra = { + extra={ "serviceName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", "rpcName": "ListOperations", "httpResponse": http_response, @@ -3037,6 +3719,4 @@ def close(self): self._session.close() -__all__=( - 'OrganizationAddressGroupServiceRestTransport', -) +__all__ = ("OrganizationAddressGroupServiceRestTransport",) diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py similarity index 51% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py index 8aa0195a0747..88b931fdd237 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/services/organization_address_group_service/transports/rest_base.py @@ -14,25 +14,25 @@ # limitations under the License. # import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import OrganizationAddressGroupServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format -from google.cloud.network_security_v1.types import address_group from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.longrunning import operations_pb2 # type: ignore +from google.cloud.network_security_v1.types import address_group +from .base import DEFAULT_CLIENT_INFO, OrganizationAddressGroupServiceTransport -class _BaseOrganizationAddressGroupServiceRestTransport(OrganizationAddressGroupServiceTransport): + +class _BaseOrganizationAddressGroupServiceRestTransport( + OrganizationAddressGroupServiceTransport +): """Base REST backend transport for OrganizationAddressGroupService. Note: This class is not meant to be used directly. Use its sync and @@ -45,14 +45,16 @@ class _BaseOrganizationAddressGroupServiceRestTransport(OrganizationAddressGroup It sends JSON representations of protocol buffers over HTTP/1.1 """ - def __init__(self, *, - host: str = 'networksecurity.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "networksecurity.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: host (Optional[str]): @@ -76,7 +78,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -87,27 +91,31 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseAddAddressGroupItems: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{address_group=organizations/*/locations/*/addressGroups/*}:addItems', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{address_group=organizations/*/locations/*/addressGroups/*}:addItems", + "body": "*", + }, ] return http_options @@ -122,17 +130,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationAddressGroupServiceRestTransport._BaseAddAddressGroupItems._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -141,20 +155,24 @@ class _BaseCloneAddressGroupItems: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{address_group=organizations/*/locations/*/addressGroups/*}:cloneItems', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{address_group=organizations/*/locations/*/addressGroups/*}:cloneItems", + "body": "*", + }, ] return http_options @@ -169,17 +187,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationAddressGroupServiceRestTransport._BaseCloneAddressGroupItems._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -188,20 +212,26 @@ class _BaseCreateAddressGroup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "addressGroupId" : "", } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "addressGroupId": "", + } @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=organizations/*/locations/*}/addressGroups', - 'body': 'address_group', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=organizations/*/locations/*}/addressGroups", + "body": "address_group", + }, ] return http_options @@ -216,17 +246,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationAddressGroupServiceRestTransport._BaseCreateAddressGroup._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -235,19 +271,23 @@ class _BaseDeleteAddressGroup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/locations/*/addressGroups/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/addressGroups/*}", + }, ] return http_options @@ -259,11 +299,17 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationAddressGroupServiceRestTransport._BaseDeleteAddressGroup._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -272,19 +318,23 @@ class _BaseGetAddressGroup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*/addressGroups/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/addressGroups/*}", + }, ] return http_options @@ -296,11 +346,17 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationAddressGroupServiceRestTransport._BaseGetAddressGroup._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -309,19 +365,23 @@ class _BaseListAddressGroupReferences: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{address_group=organizations/*/locations/*/addressGroups/*}:listReferences', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{address_group=organizations/*/locations/*/addressGroups/*}:listReferences", + }, ] return http_options @@ -333,11 +393,17 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroupReferences._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -346,19 +412,23 @@ class _BaseListAddressGroups: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=organizations/*/locations/*}/addressGroups', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*}/addressGroups", + }, ] return http_options @@ -370,11 +440,17 @@ def _get_transcoded_request(http_options, request): @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationAddressGroupServiceRestTransport._BaseListAddressGroups._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -383,20 +459,24 @@ class _BaseRemoveAddressGroupItems: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{address_group=organizations/*/locations/*/addressGroups/*}:removeItems', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{address_group=organizations/*/locations/*/addressGroups/*}:removeItems", + "body": "*", + }, ] return http_options @@ -411,17 +491,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationAddressGroupServiceRestTransport._BaseRemoveAddressGroupItems._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -430,20 +516,24 @@ class _BaseUpdateAddressGroup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{address_group.name=organizations/*/locations/*/addressGroups/*}', - 'body': 'address_group', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{address_group.name=organizations/*/locations/*/addressGroups/*}", + "body": "address_group", + }, ] return http_options @@ -458,17 +548,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_unset_required_fields(query_params)) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseOrganizationAddressGroupServiceRestTransport._BaseUpdateAddressGroup._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -479,27 +575,27 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseListLocations: @@ -508,27 +604,27 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/locations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseGetIamPolicy: @@ -537,39 +633,39 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/addressGroups/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:getIamPolicy", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseSetIamPolicy: @@ -578,48 +674,49 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/addressGroups/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:setIamPolicy", + "body": "*", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) + body = json.dumps(transcoded_request["body"]) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseTestIamPermissions: @@ -628,48 +725,49 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/authorizationPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/addressGroups/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=organizations/*/locations/*/addressGroups/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/serverTlsPolicies/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/locations/*/clientTlsPolicies/*}:testIamPermissions", + "body": "*", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) + body = json.dumps(transcoded_request["body"]) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseCancelOperation: @@ -678,33 +776,34 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}:cancel', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}:cancel", + "body": "*", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) + body = json.dumps(transcoded_request["body"]) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseDeleteOperation: @@ -713,27 +812,27 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'delete', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "delete", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseGetOperation: @@ -742,27 +841,27 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*/operations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*/operations/*}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params class _BaseListOperations: @@ -771,30 +870,28 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=organizations/*/locations/*}/operations', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=organizations/*/locations/*}/operations", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) return transcoded_request @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) return query_params -__all__=( - '_BaseOrganizationAddressGroupServiceRestTransport', -) +__all__ = ("_BaseOrganizationAddressGroupServiceRestTransport",) diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/__init__.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/__init__.py index d2d984499bf2..7204c563ea40 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/__init__.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/__init__.py @@ -13,6 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .address_group import ( + AddAddressGroupItemsRequest, + AddressGroup, + CloneAddressGroupItemsRequest, + CreateAddressGroupRequest, + DeleteAddressGroupRequest, + GetAddressGroupRequest, + ListAddressGroupReferencesRequest, + ListAddressGroupReferencesResponse, + ListAddressGroupsRequest, + ListAddressGroupsResponse, + RemoveAddressGroupItemsRequest, + UpdateAddressGroupRequest, +) from .authorization_policy import ( AuthorizationPolicy, CreateAuthorizationPolicyRequest, @@ -49,6 +63,18 @@ ) __all__ = ( + "AddAddressGroupItemsRequest", + "AddressGroup", + "CloneAddressGroupItemsRequest", + "CreateAddressGroupRequest", + "DeleteAddressGroupRequest", + "GetAddressGroupRequest", + "ListAddressGroupReferencesRequest", + "ListAddressGroupReferencesResponse", + "ListAddressGroupsRequest", + "ListAddressGroupsResponse", + "RemoveAddressGroupItemsRequest", + "UpdateAddressGroupRequest", "AuthorizationPolicy", "CreateAuthorizationPolicyRequest", "DeleteAuthorizationPolicyRequest", diff --git a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/address_group.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/address_group.py similarity index 95% rename from owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/address_group.py rename to packages/google-cloud-network-security/google/cloud/network_security_v1/types/address_group.py index b3f727df5c06..31801b15812e 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/google/cloud/network_security_v1/types/address_group.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/address_group.py @@ -17,27 +17,25 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.cloud.networksecurity.v1', + package="google.cloud.networksecurity.v1", manifest={ - 'AddressGroup', - 'ListAddressGroupsRequest', - 'ListAddressGroupsResponse', - 'GetAddressGroupRequest', - 'CreateAddressGroupRequest', - 'UpdateAddressGroupRequest', - 'DeleteAddressGroupRequest', - 'AddAddressGroupItemsRequest', - 'RemoveAddressGroupItemsRequest', - 'CloneAddressGroupItemsRequest', - 'ListAddressGroupReferencesRequest', - 'ListAddressGroupReferencesResponse', + "AddressGroup", + "ListAddressGroupsRequest", + "ListAddressGroupsResponse", + "GetAddressGroupRequest", + "CreateAddressGroupRequest", + "UpdateAddressGroupRequest", + "DeleteAddressGroupRequest", + "AddAddressGroupItemsRequest", + "RemoveAddressGroupItemsRequest", + "CloneAddressGroupItemsRequest", + "ListAddressGroupReferencesRequest", + "ListAddressGroupReferencesResponse", }, ) @@ -77,6 +75,7 @@ class AddressGroup(proto.Message): Optional. List of supported purposes of the Address Group. """ + class Type(proto.Enum): r"""Possible type of the Address Group. @@ -214,10 +213,10 @@ class ListAddressGroupsResponse(proto.Message): def raw_page(self): return self - address_groups: MutableSequence['AddressGroup'] = proto.RepeatedField( + address_groups: MutableSequence["AddressGroup"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AddressGroup', + message="AddressGroup", ) next_page_token: str = proto.Field( proto.STRING, @@ -289,10 +288,10 @@ class CreateAddressGroupRequest(proto.Message): proto.STRING, number=2, ) - address_group: 'AddressGroup' = proto.Field( + address_group: "AddressGroup" = proto.Field( proto.MESSAGE, number=3, - message='AddressGroup', + message="AddressGroup", ) request_id: str = proto.Field( proto.STRING, @@ -340,10 +339,10 @@ class UpdateAddressGroupRequest(proto.Message): number=1, message=field_mask_pb2.FieldMask, ) - address_group: 'AddressGroup' = proto.Field( + address_group: "AddressGroup" = proto.Field( proto.MESSAGE, number=2, - message='AddressGroup', + message="AddressGroup", ) request_id: str = proto.Field( proto.STRING, @@ -611,7 +610,9 @@ class AddressGroupReference(proto.Message): def raw_page(self): return self - address_group_references: MutableSequence[AddressGroupReference] = proto.RepeatedField( + address_group_references: MutableSequence[ + AddressGroupReference + ] = proto.RepeatedField( proto.MESSAGE, number=1, message=AddressGroupReference, diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_create_address_group_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_delete_address_group_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_get_address_group_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_list_address_groups_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_address_group_service_update_address_group_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py diff --git a/owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py b/packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-network-security/v1/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py rename to packages/google-cloud-network-security/samples/generated_samples/networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py diff --git a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json index 71edaea2e319..ff3746a9796b 100644 --- a/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json +++ b/packages/google-cloud-network-security/samples/generated_samples/snippet_metadata_google.cloud.networksecurity.v1.json @@ -16,34 +16,30 @@ "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_authorization_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.add_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.AddAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "CreateAuthorizationPolicy" + "shortName": "AddAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" - }, - { - "name": "authorization_policy_id", - "type": "str" + "name": "items", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -59,21 +55,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_authorization_policy" + "shortName": "add_address_group_items" }, - "description": "Sample for CreateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py", + "description": "Sample for AddAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_add_address_group_items_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_async", + "regionTag": "networksecurity_v1_generated_AddressGroupService_AddAddressGroupItems_async", "segments": [ { - "end": 61, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 56, "start": 27, "type": "SHORT" }, @@ -83,55 +79,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py" + "title": "networksecurity_v1_generated_address_group_service_add_address_group_items_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_authorization_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.add_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.AddAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "CreateAuthorizationPolicy" + "shortName": "AddAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" - }, - { - "name": "authorization_policy_id", - "type": "str" + "name": "items", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -147,21 +139,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_authorization_policy" + "shortName": "add_address_group_items" }, - "description": "Sample for CreateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py", + "description": "Sample for AddAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync", + "regionTag": "networksecurity_v1_generated_AddressGroupService_AddAddressGroupItems_sync", "segments": [ { - "end": 61, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 56, "start": 27, "type": "SHORT" }, @@ -171,55 +163,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py" + "title": "networksecurity_v1_generated_address_group_service_add_address_group_items_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_client_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.clone_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CloneAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "CreateClientTlsPolicy" + "shortName": "CloneAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" - }, - { - "name": "client_tls_policy_id", + "name": "source_address_group", "type": "str" }, { @@ -236,21 +224,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_client_tls_policy" + "shortName": "clone_address_group_items" }, - "description": "Sample for CreateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py", + "description": "Sample for CloneAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_AddressGroupService_CloneAddressGroupItems_async", "segments": [ { - "end": 60, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 56, "start": 27, "type": "SHORT" }, @@ -260,54 +248,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py" + "title": "networksecurity_v1_generated_address_group_service_clone_address_group_items_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_client_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.clone_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CloneAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "CreateClientTlsPolicy" + "shortName": "CloneAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" - }, - { - "name": "client_tls_policy_id", + "name": "source_address_group", "type": "str" }, { @@ -324,21 +308,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_client_tls_policy" + "shortName": "clone_address_group_items" }, - "description": "Sample for CreateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py", + "description": "Sample for CloneAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_AddressGroupService_CloneAddressGroupItems_sync", "segments": [ { - "end": 60, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 56, "start": 27, "type": "SHORT" }, @@ -348,55 +332,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py" + "title": "networksecurity_v1_generated_address_group_service_clone_address_group_items_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_server_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.create_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CreateAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "CreateServerTlsPolicy" + "shortName": "CreateAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" }, { "name": "parent", "type": "str" }, { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" }, { - "name": "server_tls_policy_id", + "name": "address_group_id", "type": "str" }, { @@ -413,21 +397,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_server_tls_policy" + "shortName": "create_address_group" }, - "description": "Sample for CreateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py", + "description": "Sample for CreateAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_create_address_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_AddressGroupService_CreateAddressGroup_async", "segments": [ { - "end": 60, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 62, "start": 27, "type": "SHORT" }, @@ -437,54 +421,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py" + "title": "networksecurity_v1_generated_address_group_service_create_address_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_server_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.create_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.CreateAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "CreateServerTlsPolicy" + "shortName": "CreateAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" }, { "name": "parent", "type": "str" }, { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" }, { - "name": "server_tls_policy_id", + "name": "address_group_id", "type": "str" }, { @@ -501,21 +485,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_server_tls_policy" + "shortName": "create_address_group" }, - "description": "Sample for CreateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py", + "description": "Sample for CreateAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_create_address_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_AddressGroupService_CreateAddressGroup_sync", "segments": [ { - "end": 60, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 62, "start": 27, "type": "SHORT" }, @@ -525,44 +509,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py" + "title": "networksecurity_v1_generated_address_group_service_create_address_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_authorization_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.delete_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.DeleteAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "DeleteAuthorizationPolicy" + "shortName": "DeleteAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" }, { "name": "name", @@ -582,13 +566,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_authorization_policy" + "shortName": "delete_address_group" }, - "description": "Sample for DeleteAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py", + "description": "Sample for DeleteAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_delete_address_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async", + "regionTag": "networksecurity_v1_generated_AddressGroupService_DeleteAddressGroup_async", "segments": [ { "end": 55, @@ -621,28 +605,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py" + "title": "networksecurity_v1_generated_address_group_service_delete_address_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_authorization_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.delete_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.DeleteAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "DeleteAuthorizationPolicy" + "shortName": "DeleteAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" }, { "name": "name", @@ -662,13 +646,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_authorization_policy" + "shortName": "delete_address_group" }, - "description": "Sample for DeleteAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py", + "description": "Sample for DeleteAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_delete_address_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync", + "regionTag": "networksecurity_v1_generated_AddressGroupService_DeleteAddressGroup_sync", "segments": [ { "end": 55, @@ -701,29 +685,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py" + "title": "networksecurity_v1_generated_address_group_service_delete_address_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_client_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.get_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.GetAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "DeleteClientTlsPolicy" + "shortName": "GetAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" }, { "name": "name", @@ -742,22 +726,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_client_tls_policy" + "resultType": "google.cloud.network_security_v1.types.AddressGroup", + "shortName": "get_address_group" }, - "description": "Sample for DeleteClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py", + "description": "Sample for GetAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_get_address_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_AddressGroupService_GetAddressGroup_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -772,38 +756,38 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py" + "title": "networksecurity_v1_generated_address_group_service_get_address_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_client_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.get_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.GetAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "DeleteClientTlsPolicy" + "shortName": "GetAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" }, { "name": "name", @@ -822,22 +806,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_client_tls_policy" + "resultType": "google.cloud.network_security_v1.types.AddressGroup", + "shortName": "get_address_group" }, - "description": "Sample for DeleteClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py", + "description": "Sample for GetAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_get_address_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_AddressGroupService_GetAddressGroup_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -852,42 +836,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py" + "title": "networksecurity_v1_generated_address_group_service_get_address_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_server_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.list_address_group_references", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroupReferences", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "DeleteServerTlsPolicy" + "shortName": "ListAddressGroupReferences" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" }, { - "name": "name", + "name": "address_group", "type": "str" }, { @@ -903,22 +887,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_server_tls_policy" + "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupReferencesAsyncPager", + "shortName": "list_address_group_references" }, - "description": "Sample for DeleteServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py", + "description": "Sample for ListAddressGroupReferences", + "file": "networksecurity_v1_generated_address_group_service_list_address_group_references_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroupReferences_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -933,41 +917,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py" + "title": "networksecurity_v1_generated_address_group_service_list_address_group_references_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_server_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.list_address_group_references", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroupReferences", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "DeleteServerTlsPolicy" + "shortName": "ListAddressGroupReferences" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" }, { - "name": "name", + "name": "address_group", "type": "str" }, { @@ -983,22 +967,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_server_tls_policy" + "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupReferencesPager", + "shortName": "list_address_group_references" }, - "description": "Sample for DeleteServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py", + "description": "Sample for ListAddressGroupReferences", + "file": "networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroupReferences_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1013,42 +997,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py" + "title": "networksecurity_v1_generated_address_group_service_list_address_group_references_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_authorization_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.list_address_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "GetAuthorizationPolicy" + "shortName": "ListAddressGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -1064,22 +1048,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", - "shortName": "get_authorization_policy" + "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupsAsyncPager", + "shortName": "list_address_groups" }, - "description": "Sample for GetAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py", + "description": "Sample for ListAddressGroups", + "file": "networksecurity_v1_generated_address_group_service_list_address_groups_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_async", + "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroups_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1099,36 +1083,36 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py" + "title": "networksecurity_v1_generated_address_group_service_list_address_groups_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_authorization_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.list_address_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.ListAddressGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "GetAuthorizationPolicy" + "shortName": "ListAddressGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -1144,22 +1128,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", - "shortName": "get_authorization_policy" + "resultType": "google.cloud.network_security_v1.services.address_group_service.pagers.ListAddressGroupsPager", + "shortName": "list_address_groups" }, - "description": "Sample for GetAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py", + "description": "Sample for ListAddressGroups", + "file": "networksecurity_v1_generated_address_group_service_list_address_groups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_sync", + "regionTag": "networksecurity_v1_generated_AddressGroupService_ListAddressGroups_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1179,39 +1163,43 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py" + "title": "networksecurity_v1_generated_address_group_service_list_address_groups_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_client_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.remove_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.RemoveAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "GetClientTlsPolicy" + "shortName": "RemoveAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" }, { - "name": "name", + "name": "address_group", "type": "str" }, + { + "name": "items", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1225,22 +1213,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", - "shortName": "get_client_tls_policy" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "remove_address_group_items" }, - "description": "Sample for GetClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py", + "description": "Sample for RemoveAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_AddressGroupService_RemoveAddressGroupItems_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -1250,48 +1238,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py" + "title": "networksecurity_v1_generated_address_group_service_remove_address_group_items_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_client_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.remove_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.RemoveAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "GetClientTlsPolicy" + "shortName": "RemoveAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" }, { - "name": "name", + "name": "address_group", "type": "str" }, + { + "name": "items", + "type": "MutableSequence[str]" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1305,22 +1297,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", - "shortName": "get_client_tls_policy" + "resultType": "google.api_core.operation.Operation", + "shortName": "remove_address_group_items" }, - "description": "Sample for GetClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py", + "description": "Sample for RemoveAddressGroupItems", + "file": "networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_AddressGroupService_RemoveAddressGroupItems_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -1330,48 +1322,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py" + "title": "networksecurity_v1_generated_address_group_service_remove_address_group_items_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient", + "shortName": "AddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_server_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceAsyncClient.update_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.UpdateAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "GetServerTlsPolicy" + "shortName": "UpdateAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" }, { - "name": "name", - "type": "str" + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -1386,22 +1382,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", - "shortName": "get_server_tls_policy" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_address_group" }, - "description": "Sample for GetServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py", + "description": "Sample for UpdateAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_update_address_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_AddressGroupService_UpdateAddressGroup_async", "segments": [ { - "end": 51, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 60, "start": 27, "type": "SHORT" }, @@ -1411,47 +1407,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py" + "title": "networksecurity_v1_generated_address_group_service_update_address_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient", + "shortName": "AddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_server_tls_policy", + "fullName": "google.cloud.network_security_v1.AddressGroupServiceClient.update_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.AddressGroupService.UpdateAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.AddressGroupService", + "shortName": "AddressGroupService" }, - "shortName": "GetServerTlsPolicy" + "shortName": "UpdateAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" }, { - "name": "name", - "type": "str" + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -1466,22 +1466,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", - "shortName": "get_server_tls_policy" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_address_group" }, - "description": "Sample for GetServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py", + "description": "Sample for UpdateAddressGroup", + "file": "networksecurity_v1_generated_address_group_service_update_address_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_AddressGroupService_UpdateAddressGroup_sync", "segments": [ { - "end": 51, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 60, "start": 27, "type": "SHORT" }, @@ -1491,22 +1491,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py" + "title": "networksecurity_v1_generated_address_group_service_update_address_group_sync.py" }, { "canonical": true, @@ -1516,24 +1516,32 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_authorization_policies", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_authorization_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "ListAuthorizationPolicies" + "shortName": "CreateAuthorizationPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" + "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" }, { "name": "parent", "type": "str" }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "authorization_policy_id", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1547,22 +1555,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager", - "shortName": "list_authorization_policies" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_authorization_policy" }, - "description": "Sample for ListAuthorizationPolicies", - "file": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py", + "description": "Sample for CreateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_async", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_async", "segments": [ { - "end": 52, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 61, "start": 27, "type": "SHORT" }, @@ -1572,22 +1580,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py" + "title": "networksecurity_v1_generated_network_security_create_authorization_policy_async.py" }, { "canonical": true, @@ -1596,24 +1604,32 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", "shortName": "NetworkSecurityClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_authorization_policies", + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_authorization_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateAuthorizationPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "ListAuthorizationPolicies" + "shortName": "CreateAuthorizationPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" + "type": "google.cloud.network_security_v1.types.CreateAuthorizationPolicyRequest" }, { "name": "parent", "type": "str" }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "authorization_policy_id", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1627,22 +1643,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesPager", - "shortName": "list_authorization_policies" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_authorization_policy" }, - "description": "Sample for ListAuthorizationPolicies", - "file": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py", + "description": "Sample for CreateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_sync", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateAuthorizationPolicy_sync", "segments": [ { - "end": 52, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 61, "start": 27, "type": "SHORT" }, @@ -1652,22 +1668,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py" + "title": "networksecurity_v1_generated_network_security_create_authorization_policy_sync.py" }, { "canonical": true, @@ -1677,22 +1693,3008 @@ "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", "shortName": "NetworkSecurityAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_client_tls_policies", + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_client_tls_policy", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "client_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_client_tls_policy" + }, + "description": "Sample for CreateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateClientTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "client_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_client_tls_policy" + }, + "description": "Sample for CreateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateClientTlsPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.create_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", "service": { "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", "shortName": "NetworkSecurity" }, - "shortName": "ListClientTlsPolicies" + "shortName": "CreateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "server_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_server_tls_policy" + }, + "description": "Sample for CreateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.create_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.CreateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "CreateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateServerTlsPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "server_tls_policy_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_server_tls_policy" + }, + "description": "Sample for CreateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_CreateServerTlsPolicy_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_create_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_authorization_policy" + }, + "description": "Sample for DeleteAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_authorization_policy" + }, + "description": "Sample for DeleteAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteAuthorizationPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_client_tls_policy" + }, + "description": "Sample for DeleteClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_client_tls_policy" + }, + "description": "Sample for DeleteClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteClientTlsPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.delete_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_server_tls_policy" + }, + "description": "Sample for DeleteServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.delete_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.DeleteServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "DeleteServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_server_tls_policy" + }, + "description": "Sample for DeleteServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_DeleteServerTlsPolicy_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_delete_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", + "shortName": "get_authorization_policy" + }, + "description": "Sample for GetAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetAuthorizationPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.AuthorizationPolicy", + "shortName": "get_authorization_policy" + }, + "description": "Sample for GetAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetAuthorizationPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", + "shortName": "get_client_tls_policy" + }, + "description": "Sample for GetClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetClientTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.ClientTlsPolicy", + "shortName": "get_client_tls_policy" + }, + "description": "Sample for GetClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetClientTlsPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.get_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", + "shortName": "get_server_tls_policy" + }, + "description": "Sample for GetServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.get_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.GetServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "GetServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.GetServerTlsPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.types.ServerTlsPolicy", + "shortName": "get_server_tls_policy" + }, + "description": "Sample for GetServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_GetServerTlsPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_get_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_authorization_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListAuthorizationPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesAsyncPager", + "shortName": "list_authorization_policies" + }, + "description": "Sample for ListAuthorizationPolicies", + "file": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_authorization_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_authorization_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListAuthorizationPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListAuthorizationPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListAuthorizationPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListAuthorizationPoliciesPager", + "shortName": "list_authorization_policies" + }, + "description": "Sample for ListAuthorizationPolicies", + "file": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListAuthorizationPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_authorization_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_client_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListClientTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager", + "shortName": "list_client_tls_policies" + }, + "description": "Sample for ListClientTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_client_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListClientTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesPager", + "shortName": "list_client_tls_policies" + }, + "description": "Sample for ListClientTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_server_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListServerTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager", + "shortName": "list_server_tls_policies" + }, + "description": "Sample for ListServerTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_server_tls_policies", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "ListServerTlsPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesPager", + "shortName": "list_server_tls_policies" + }, + "description": "Sample for ListServerTlsPolicies", + "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_authorization_policy" + }, + "description": "Sample for UpdateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_authorization_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateAuthorizationPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" + }, + { + "name": "authorization_policy", + "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_authorization_policy" + }, + "description": "Sample for UpdateAuthorizationPolicy", + "file": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_client_tls_policy" + }, + "description": "Sample for UpdateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_client_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateClientTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" + }, + { + "name": "client_tls_policy", + "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_client_tls_policy" + }, + "description": "Sample for UpdateClientTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", + "shortName": "NetworkSecurityAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_server_tls_policy" + }, + "description": "Sample for UpdateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", + "shortName": "NetworkSecurityClient" + }, + "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_server_tls_policy", + "method": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", + "service": { + "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", + "shortName": "NetworkSecurity" + }, + "shortName": "UpdateServerTlsPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" + }, + { + "name": "server_tls_policy", + "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_server_tls_policy" + }, + "description": "Sample for UpdateServerTlsPolicy", + "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.add_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.AddAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "AddAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "items", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "add_address_group_items" + }, + "description": "Sample for AddAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.add_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.AddAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "AddAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.AddAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "items", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "add_address_group_items" + }, + "description": "Sample for AddAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_AddAddressGroupItems_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_add_address_group_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.clone_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CloneAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "CloneAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "source_address_group", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "clone_address_group_items" + }, + "description": "Sample for CloneAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.clone_address_group_items", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CloneAddressGroupItems", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "CloneAddressGroupItems" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CloneAddressGroupItemsRequest" + }, + { + "name": "address_group", + "type": "str" + }, + { + "name": "source_address_group", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "clone_address_group_items" + }, + "description": "Sample for CloneAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CloneAddressGroupItems_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_clone_address_group_items_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.create_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CreateAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "CreateAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "address_group_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_address_group" + }, + "description": "Sample for CreateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_create_address_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.create_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.CreateAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "CreateAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.CreateAddressGroupRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" + }, + { + "name": "address_group_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_address_group" + }, + "description": "Sample for CreateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_CreateAddressGroup_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_create_address_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.delete_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.DeleteAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "DeleteAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_address_group" + }, + "description": "Sample for DeleteAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.delete_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.DeleteAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "DeleteAddressGroup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.network_security_v1.types.DeleteAddressGroupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_address_group" + }, + "description": "Sample for DeleteAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_DeleteAddressGroup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networksecurity_v1_generated_organization_address_group_service_delete_address_group_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" + }, + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.get_address_group", + "method": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.GetAddressGroup", + "service": { + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" + }, + "shortName": "GetAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" + "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -1708,22 +4710,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesAsyncPager", - "shortName": "list_client_tls_policies" + "resultType": "google.cloud.network_security_v1.types.AddressGroup", + "shortName": "get_address_group" }, - "description": "Sample for ListClientTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py", + "description": "Sample for GetAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1743,36 +4745,36 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_get_address_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_client_tls_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.get_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListClientTlsPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.GetAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListClientTlsPolicies" + "shortName": "GetAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListClientTlsPoliciesRequest" + "type": "google.cloud.network_security_v1.types.GetAddressGroupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -1788,22 +4790,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListClientTlsPoliciesPager", - "shortName": "list_client_tls_policies" + "resultType": "google.cloud.network_security_v1.types.AddressGroup", + "shortName": "get_address_group" }, - "description": "Sample for ListClientTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py", + "description": "Sample for GetAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListClientTlsPolicies_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_GetAddressGroup_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1823,37 +4825,37 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_client_tls_policies_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_get_address_group_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.list_server_tls_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.list_address_group_references", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroupReferences", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListServerTlsPolicies" + "shortName": "ListAddressGroupReferences" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, { @@ -1869,14 +4871,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesAsyncPager", - "shortName": "list_server_tls_policies" + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesAsyncPager", + "shortName": "list_address_group_references" }, - "description": "Sample for ListServerTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py", + "description": "Sample for ListAddressGroupReferences", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_async", "segments": [ { "end": 52, @@ -1909,31 +4911,31 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.list_server_tls_policies", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.list_address_group_references", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.ListServerTlsPolicies", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroupReferences", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "ListServerTlsPolicies" + "shortName": "ListAddressGroupReferences" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.ListServerTlsPoliciesRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupReferencesRequest" }, { - "name": "parent", + "name": "address_group", "type": "str" }, { @@ -1949,14 +4951,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.network_security_v1.services.network_security.pagers.ListServerTlsPoliciesPager", - "shortName": "list_server_tls_policies" + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupReferencesPager", + "shortName": "list_address_group_references" }, - "description": "Sample for ListServerTlsPolicies", - "file": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py", + "description": "Sample for ListAddressGroupReferences", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_ListServerTlsPolicies_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroupReferences_sync", "segments": [ { "end": 52, @@ -1989,37 +4991,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_list_server_tls_policies_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_group_references_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_authorization_policy", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.list_address_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "UpdateAuthorizationPolicy" + "shortName": "ListAddressGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" - }, - { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" + "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -2034,22 +5032,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_authorization_policy" + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsAsyncPager", + "shortName": "list_address_groups" }, - "description": "Sample for UpdateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py", + "description": "Sample for ListAddressGroups", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_async", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2059,51 +5057,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_authorization_policy_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_authorization_policy", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.list_address_groups", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateAuthorizationPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.ListAddressGroups", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "UpdateAuthorizationPolicy" + "shortName": "ListAddressGroups" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateAuthorizationPolicyRequest" + "type": "google.cloud.network_security_v1.types.ListAddressGroupsRequest" }, { - "name": "authorization_policy", - "type": "google.cloud.network_security_v1.types.AuthorizationPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "parent", + "type": "str" }, { "name": "retry", @@ -2118,22 +5112,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_authorization_policy" + "resultType": "google.cloud.network_security_v1.services.organization_address_group_service.pagers.ListAddressGroupsPager", + "shortName": "list_address_groups" }, - "description": "Sample for UpdateAuthorizationPolicy", - "file": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py", + "description": "Sample for ListAddressGroups", + "file": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateAuthorizationPolicy_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_ListAddressGroups_sync", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2143,52 +5137,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_authorization_policy_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_list_address_groups_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_client_tls_policy", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.remove_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.RemoveAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "UpdateClientTlsPolicy" + "shortName": "RemoveAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" }, { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + "name": "address_group", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "items", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -2204,21 +5198,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_client_tls_policy" + "shortName": "remove_address_group_items" }, - "description": "Sample for UpdateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py", + "description": "Sample for RemoveAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_async", "segments": [ { - "end": 58, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 56, "start": 27, "type": "SHORT" }, @@ -2228,51 +5222,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_client_tls_policy", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.remove_address_group_items", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateClientTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.RemoveAddressGroupItems", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "UpdateClientTlsPolicy" + "shortName": "RemoveAddressGroupItems" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateClientTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.RemoveAddressGroupItemsRequest" }, { - "name": "client_tls_policy", - "type": "google.cloud.network_security_v1.types.ClientTlsPolicy" + "name": "address_group", + "type": "str" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "items", + "type": "MutableSequence[str]" }, { "name": "retry", @@ -2288,21 +5282,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_client_tls_policy" + "shortName": "remove_address_group_items" }, - "description": "Sample for UpdateClientTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py", + "description": "Sample for RemoveAddressGroupItems", + "file": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateClientTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_RemoveAddressGroupItems_sync", "segments": [ { - "end": 58, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 56, "start": 27, "type": "SHORT" }, @@ -2312,48 +5306,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_client_tls_policy_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_remove_address_group_items_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient", - "shortName": "NetworkSecurityAsyncClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient", + "shortName": "OrganizationAddressGroupServiceAsyncClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityAsyncClient.update_server_tls_policy", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceAsyncClient.update_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.UpdateAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "UpdateServerTlsPolicy" + "shortName": "UpdateAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" }, { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" }, { "name": "update_mask", @@ -2373,21 +5367,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_server_tls_policy" + "shortName": "update_address_group" }, - "description": "Sample for UpdateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py", + "description": "Sample for UpdateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_async", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_async", "segments": [ { - "end": 58, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 60, "start": 27, "type": "SHORT" }, @@ -2397,47 +5391,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_async.py" + "title": "networksecurity_v1_generated_organization_address_group_service_update_address_group_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient", - "shortName": "NetworkSecurityClient" + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient", + "shortName": "OrganizationAddressGroupServiceClient" }, - "fullName": "google.cloud.network_security_v1.NetworkSecurityClient.update_server_tls_policy", + "fullName": "google.cloud.network_security_v1.OrganizationAddressGroupServiceClient.update_address_group", "method": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity.UpdateServerTlsPolicy", + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService.UpdateAddressGroup", "service": { - "fullName": "google.cloud.networksecurity.v1.NetworkSecurity", - "shortName": "NetworkSecurity" + "fullName": "google.cloud.networksecurity.v1.OrganizationAddressGroupService", + "shortName": "OrganizationAddressGroupService" }, - "shortName": "UpdateServerTlsPolicy" + "shortName": "UpdateAddressGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.network_security_v1.types.UpdateServerTlsPolicyRequest" + "type": "google.cloud.network_security_v1.types.UpdateAddressGroupRequest" }, { - "name": "server_tls_policy", - "type": "google.cloud.network_security_v1.types.ServerTlsPolicy" + "name": "address_group", + "type": "google.cloud.network_security_v1.types.AddressGroup" }, { "name": "update_mask", @@ -2457,21 +5451,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_server_tls_policy" + "shortName": "update_address_group" }, - "description": "Sample for UpdateServerTlsPolicy", - "file": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py", + "description": "Sample for UpdateAddressGroup", + "file": "networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networksecurity_v1_generated_NetworkSecurity_UpdateServerTlsPolicy_sync", + "regionTag": "networksecurity_v1_generated_OrganizationAddressGroupService_UpdateAddressGroup_sync", "segments": [ { - "end": 58, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 60, "start": 27, "type": "SHORT" }, @@ -2481,22 +5475,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 49, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "networksecurity_v1_generated_network_security_update_server_tls_policy_sync.py" + "title": "networksecurity_v1_generated_organization_address_group_service_update_address_group_sync.py" } ] } diff --git a/packages/google-cloud-network-security/scripts/fixup_network_security_v1_keywords.py b/packages/google-cloud-network-security/scripts/fixup_network_security_v1_keywords.py index f383005222af..4404e816019e 100644 --- a/packages/google-cloud-network-security/scripts/fixup_network_security_v1_keywords.py +++ b/packages/google-cloud-network-security/scripts/fixup_network_security_v1_keywords.py @@ -39,18 +39,27 @@ def partition( class network_securityCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_address_group_items': ('address_group', 'items', 'request_id', ), + 'clone_address_group_items': ('address_group', 'source_address_group', 'request_id', ), + 'create_address_group': ('parent', 'address_group_id', 'address_group', 'request_id', ), 'create_authorization_policy': ('parent', 'authorization_policy_id', 'authorization_policy', ), 'create_client_tls_policy': ('parent', 'client_tls_policy_id', 'client_tls_policy', ), 'create_server_tls_policy': ('parent', 'server_tls_policy_id', 'server_tls_policy', ), + 'delete_address_group': ('name', 'request_id', ), 'delete_authorization_policy': ('name', ), 'delete_client_tls_policy': ('name', ), 'delete_server_tls_policy': ('name', ), + 'get_address_group': ('name', ), 'get_authorization_policy': ('name', ), 'get_client_tls_policy': ('name', ), 'get_server_tls_policy': ('name', ), + 'list_address_group_references': ('address_group', 'page_size', 'page_token', ), + 'list_address_groups': ('parent', 'page_size', 'page_token', 'return_partial_success', ), 'list_authorization_policies': ('parent', 'page_size', 'page_token', ), 'list_client_tls_policies': ('parent', 'page_size', 'page_token', ), 'list_server_tls_policies': ('parent', 'page_size', 'page_token', ), + 'remove_address_group_items': ('address_group', 'items', 'request_id', ), + 'update_address_group': ('address_group', 'update_mask', 'request_id', ), 'update_authorization_policy': ('authorization_policy', 'update_mask', ), 'update_client_tls_policy': ('client_tls_policy', 'update_mask', ), 'update_server_tls_policy': ('server_tls_policy', 'update_mask', ), diff --git a/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_address_group_service.py b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_address_group_service.py similarity index 72% rename from owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_address_group_service.py rename to packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_address_group_service.py index 54906348d6ad..eb46e6657a98 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_address_group_service.py +++ b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_address_group_service.py @@ -14,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,59 +22,62 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format +from collections.abc import AsyncIterable, Iterable import json import math -import pytest + from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from google.protobuf import json_format +import grpc +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.protobuf import json_format try: from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) from google.api_core import client_options from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template from google.api_core import retry as retries +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.location import locations_pb2 -from google.cloud.network_security_v1.services.address_group_service import AddressGroupServiceAsyncClient -from google.cloud.network_security_v1.services.address_group_service import AddressGroupServiceClient -from google.cloud.network_security_v1.services.address_group_service import pagers -from google.cloud.network_security_v1.services.address_group_service import transports -from google.cloud.network_security_v1.types import address_group -from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.cloud.network_security_v1.types import common from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import options_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - +from google.cloud.network_security_v1.services.address_group_service import ( + AddressGroupServiceAsyncClient, + AddressGroupServiceClient, + pagers, + transports, +) +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import common CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -88,9 +92,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -98,17 +104,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # 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 + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -119,101 +135,243 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert AddressGroupServiceClient._get_default_mtls_endpoint(None) is None - assert AddressGroupServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AddressGroupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AddressGroupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AddressGroupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AddressGroupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + AddressGroupServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + AddressGroupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AddressGroupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AddressGroupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AddressGroupServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert AddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + assert AddressGroupServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AddressGroupServiceClient._read_environment_variables() == (True, "auto", None) + assert AddressGroupServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + assert AddressGroupServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError) as excinfo: AddressGroupServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert AddressGroupServiceClient._read_environment_variables() == (False, "never", None) + assert AddressGroupServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AddressGroupServiceClient._read_environment_variables() == (False, "always", None) + assert AddressGroupServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + assert AddressGroupServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: AddressGroupServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert AddressGroupServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert AddressGroupServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() assert AddressGroupServiceClient._get_client_cert_source(None, False) is None - assert AddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + AddressGroupServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + AddressGroupServiceClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + AddressGroupServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + AddressGroupServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert AddressGroupServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(AddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceClient)) -@mock.patch.object(AddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceAsyncClient)) +@mock.patch.object( + AddressGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AddressGroupServiceClient), +) +@mock.patch.object( + AddressGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AddressGroupServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = AddressGroupServiceClient._DEFAULT_UNIVERSE - default_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert AddressGroupServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT - assert AddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "always") == AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT - assert AddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT - assert AddressGroupServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + AddressGroupServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + AddressGroupServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AddressGroupServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + AddressGroupServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AddressGroupServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == AddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AddressGroupServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + AddressGroupServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - AddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + AddressGroupServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert AddressGroupServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AddressGroupServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AddressGroupServiceClient._get_universe_domain(None, None) == AddressGroupServiceClient._DEFAULT_UNIVERSE + assert ( + AddressGroupServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + AddressGroupServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + AddressGroupServiceClient._get_universe_domain(None, None) + == AddressGroupServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: AddressGroupServiceClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -229,7 +387,8 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] -@pytest.mark.parametrize("error_code", [401,403,404,500]) + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -242,14 +401,22 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] -@pytest.mark.parametrize("client_class,transport_name", [ - (AddressGroupServiceClient, "grpc"), - (AddressGroupServiceAsyncClient, "grpc_asyncio"), - (AddressGroupServiceClient, "rest"), -]) -def test_address_group_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AddressGroupServiceClient, "grpc"), + (AddressGroupServiceAsyncClient, "grpc_asyncio"), + (AddressGroupServiceClient, "rest"), + ], +) +def test_address_group_service_client_from_service_account_info( + client_class, transport_name +): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -257,52 +424,70 @@ def test_address_group_service_client_from_service_account_info(client_class, tr assert isinstance(client, client_class) assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networksecurity.googleapis.com' + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" ) -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AddressGroupServiceGrpcTransport, "grpc"), - (transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AddressGroupServiceRestTransport, "rest"), -]) -def test_address_group_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.AddressGroupServiceGrpcTransport, "grpc"), + (transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AddressGroupServiceRestTransport, "rest"), + ], +) +def test_address_group_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize("client_class,transport_name", [ - (AddressGroupServiceClient, "grpc"), - (AddressGroupServiceAsyncClient, "grpc_asyncio"), - (AddressGroupServiceClient, "rest"), -]) -def test_address_group_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AddressGroupServiceClient, "grpc"), + (AddressGroupServiceAsyncClient, "grpc_asyncio"), + (AddressGroupServiceClient, "rest"), + ], +) +def test_address_group_service_client_from_service_account_file( + client_class, transport_name +): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networksecurity.googleapis.com' + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" ) @@ -318,30 +503,53 @@ def test_address_group_service_client_get_transport_class(): assert transport == transports.AddressGroupServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc"), - (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AddressGroupServiceClient, transports.AddressGroupServiceRestTransport, "rest"), -]) -@mock.patch.object(AddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceClient)) -@mock.patch.object(AddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceAsyncClient)) -def test_address_group_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AddressGroupServiceClient, + transports.AddressGroupServiceGrpcTransport, + "grpc", + ), + ( + AddressGroupServiceAsyncClient, + transports.AddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AddressGroupServiceClient, + transports.AddressGroupServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + AddressGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AddressGroupServiceClient), +) +@mock.patch.object( + AddressGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AddressGroupServiceAsyncClient), +) +def test_address_group_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(AddressGroupServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(AddressGroupServiceClient, "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(AddressGroupServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(AddressGroupServiceClient, "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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -359,13 +567,15 @@ def test_address_group_service_client_client_options(client_class, transport_cla # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -377,7 +587,7 @@ def test_address_group_service_client_client_options(client_class, transport_cla # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -397,23 +607,33 @@ def test_address_group_service_client_client_options(client_class, transport_cla with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError) as excinfo: client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -422,48 +642,102 @@ def test_address_group_service_client_client_options(client_class, transport_cla api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc", "true"), - (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc", "false"), - (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AddressGroupServiceClient, transports.AddressGroupServiceRestTransport, "rest", "true"), - (AddressGroupServiceClient, transports.AddressGroupServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceClient)) -@mock.patch.object(AddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + AddressGroupServiceClient, + transports.AddressGroupServiceGrpcTransport, + "grpc", + "true", + ), + ( + AddressGroupServiceAsyncClient, + transports.AddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + AddressGroupServiceClient, + transports.AddressGroupServiceGrpcTransport, + "grpc", + "false", + ), + ( + AddressGroupServiceAsyncClient, + transports.AddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + AddressGroupServiceClient, + transports.AddressGroupServiceRestTransport, + "rest", + "true", + ), + ( + AddressGroupServiceClient, + transports.AddressGroupServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + AddressGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AddressGroupServiceClient), +) +@mock.patch.object( + AddressGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AddressGroupServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_address_group_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_address_group_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: + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -482,12 +756,22 @@ def test_address_group_service_client_mtls_env_auto(client_class, transport_clas # 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): + 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -508,15 +792,22 @@ def test_address_group_service_client_mtls_env_auto(client_class, transport_clas ) # 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): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -526,19 +817,31 @@ def test_address_group_service_client_mtls_env_auto(client_class, transport_clas ) -@pytest.mark.parametrize("client_class", [ - AddressGroupServiceClient, AddressGroupServiceAsyncClient -]) -@mock.patch.object(AddressGroupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AddressGroupServiceClient)) -@mock.patch.object(AddressGroupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AddressGroupServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [AddressGroupServiceClient, AddressGroupServiceAsyncClient] +) +@mock.patch.object( + AddressGroupServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AddressGroupServiceClient), +) +@mock.patch.object( + AddressGroupServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AddressGroupServiceAsyncClient), +) def test_address_group_service_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -546,8 +849,12 @@ def test_address_group_service_client_get_mtls_endpoint_and_cert_source(client_c with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source is None @@ -565,16 +872,28 @@ def test_address_group_service_client_get_mtls_endpoint_and_cert_source(client_c # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -584,34 +903,62 @@ def test_address_group_service_client_get_mtls_endpoint_and_cert_source(client_c with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + -@pytest.mark.parametrize("client_class", [ - AddressGroupServiceClient, AddressGroupServiceAsyncClient -]) -@mock.patch.object(AddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceClient)) -@mock.patch.object(AddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AddressGroupServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [AddressGroupServiceClient, AddressGroupServiceAsyncClient] +) +@mock.patch.object( + AddressGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AddressGroupServiceClient), +) +@mock.patch.object( + AddressGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AddressGroupServiceAsyncClient), +) def test_address_group_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = AddressGroupServiceClient._DEFAULT_UNIVERSE - default_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -634,11 +981,19 @@ def test_address_group_service_client_client_api_endpoint(client_class): universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -646,27 +1001,48 @@ def test_address_group_service_client_client_api_endpoint(client_class): if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc"), - (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AddressGroupServiceClient, transports.AddressGroupServiceRestTransport, "rest"), -]) -def test_address_group_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AddressGroupServiceClient, + transports.AddressGroupServiceGrpcTransport, + "grpc", + ), + ( + AddressGroupServiceAsyncClient, + transports.AddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AddressGroupServiceClient, + transports.AddressGroupServiceRestTransport, + "rest", + ), + ], +) +def test_address_group_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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -675,24 +1051,45 @@ def test_address_group_service_client_client_options_scopes(client_class, transp api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc", grpc_helpers), - (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AddressGroupServiceClient, transports.AddressGroupServiceRestTransport, "rest", None), -]) -def test_address_group_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + AddressGroupServiceClient, + transports.AddressGroupServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AddressGroupServiceAsyncClient, + transports.AddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + AddressGroupServiceClient, + transports.AddressGroupServiceRestTransport, + "rest", + None, + ), + ], +) +def test_address_group_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -701,11 +1098,14 @@ def test_address_group_service_client_client_options_credentials_file(client_cla api_audience=None, ) + def test_address_group_service_client_client_options_from_dict(): - with mock.patch('google.cloud.network_security_v1.services.address_group_service.transports.AddressGroupServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.cloud.network_security_v1.services.address_group_service.transports.AddressGroupServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = AddressGroupServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -720,23 +1120,38 @@ def test_address_group_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport, "grpc", grpc_helpers), - (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_address_group_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + AddressGroupServiceClient, + transports.AddressGroupServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AddressGroupServiceAsyncClient, + transports.AddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_address_group_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -763,9 +1178,7 @@ def test_address_group_service_client_create_channel_credentials_file(client_cla credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=None, default_host="networksecurity.googleapis.com", ssl_credentials=None, @@ -776,11 +1189,14 @@ def test_address_group_service_client_create_channel_credentials_file(client_cla ) -@pytest.mark.parametrize("request_type", [ - address_group.ListAddressGroupsRequest, - dict, -]) -def test_list_address_groups(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + address_group.ListAddressGroupsRequest, + dict, + ], +) +def test_list_address_groups(request_type, transport: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -792,12 +1208,12 @@ def test_list_address_groups(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.ListAddressGroupsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) response = client.list_address_groups(request) @@ -809,8 +1225,8 @@ def test_list_address_groups(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] def test_list_address_groups_non_empty_request_with_auto_populated_field(): @@ -818,30 +1234,33 @@ def test_list_address_groups_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = address_group.ListAddressGroupsRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_address_groups), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_address_groups(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == address_group.ListAddressGroupsRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_address_groups_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -856,12 +1275,18 @@ def test_list_address_groups_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_address_groups in client._transport._wrapped_methods + assert ( + client._transport.list_address_groups in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_address_groups] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_address_groups + ] = mock_rpc request = {} client.list_address_groups(request) @@ -874,8 +1299,11 @@ def test_list_address_groups_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_address_groups_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_address_groups_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -889,12 +1317,17 @@ async def test_list_address_groups_async_use_cached_wrapped_rpc(transport: str = wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_address_groups in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_address_groups + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_address_groups] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_address_groups + ] = mock_rpc request = {} await client.list_address_groups(request) @@ -908,8 +1341,11 @@ async def test_list_address_groups_async_use_cached_wrapped_rpc(transport: str = assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_address_groups_async(transport: str = 'grpc_asyncio', request_type=address_group.ListAddressGroupsRequest): +async def test_list_address_groups_async( + transport: str = "grpc_asyncio", request_type=address_group.ListAddressGroupsRequest +): client = AddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -921,13 +1357,15 @@ async def test_list_address_groups_async(transport: str = 'grpc_asyncio', reques # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.ListAddressGroupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) response = await client.list_address_groups(request) # Establish that the underlying gRPC stub method was called. @@ -938,14 +1376,15 @@ async def test_list_address_groups_async(transport: str = 'grpc_asyncio', reques # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio async def test_list_address_groups_async_from_dict(): await test_list_address_groups_async(request_type=dict) + def test_list_address_groups_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -955,12 +1394,12 @@ def test_list_address_groups_field_headers(): # a field header. Set these to a non-empty value. request = address_group.ListAddressGroupsRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: call.return_value = address_group.ListAddressGroupsResponse() client.list_address_groups(request) @@ -972,9 +1411,9 @@ def test_list_address_groups_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -987,13 +1426,15 @@ async def test_list_address_groups_field_headers_async(): # a field header. Set these to a non-empty value. request = address_group.ListAddressGroupsRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse()) + type(client.transport.list_address_groups), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.ListAddressGroupsResponse() + ) await client.list_address_groups(request) # Establish that the underlying gRPC stub method was called. @@ -1004,9 +1445,9 @@ async def test_list_address_groups_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_list_address_groups_flattened(): @@ -1016,14 +1457,14 @@ def test_list_address_groups_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.ListAddressGroupsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_address_groups( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1031,7 +1472,7 @@ def test_list_address_groups_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val @@ -1045,9 +1486,10 @@ def test_list_address_groups_flattened_error(): with pytest.raises(ValueError): client.list_address_groups( address_group.ListAddressGroupsRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_address_groups_flattened_async(): client = AddressGroupServiceAsyncClient( @@ -1056,16 +1498,18 @@ async def test_list_address_groups_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.ListAddressGroupsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.ListAddressGroupsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_address_groups( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1073,9 +1517,10 @@ async def test_list_address_groups_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val + @pytest.mark.asyncio async def test_list_address_groups_flattened_error_async(): client = AddressGroupServiceAsyncClient( @@ -1087,7 +1532,7 @@ async def test_list_address_groups_flattened_error_async(): with pytest.raises(ValueError): await client.list_address_groups( address_group.ListAddressGroupsRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1099,8 +1544,8 @@ def test_list_address_groups_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( address_group.ListAddressGroupsResponse( @@ -1109,17 +1554,17 @@ def test_list_address_groups_pager(transport_name: str = "grpc"): address_group.AddressGroup(), address_group.AddressGroup(), ], - next_page_token='abc', + next_page_token="abc", ), address_group.ListAddressGroupsResponse( address_groups=[], - next_page_token='def', + next_page_token="def", ), address_group.ListAddressGroupsResponse( address_groups=[ address_group.AddressGroup(), ], - next_page_token='ghi', + next_page_token="ghi", ), address_group.ListAddressGroupsResponse( address_groups=[ @@ -1134,9 +1579,7 @@ def test_list_address_groups_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) pager = client.list_address_groups(request={}, retry=retry, timeout=timeout) @@ -1146,8 +1589,9 @@ def test_list_address_groups_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, address_group.AddressGroup) - for i in results) + assert all(isinstance(i, address_group.AddressGroup) for i in results) + + def test_list_address_groups_pages(transport_name: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1156,8 +1600,8 @@ def test_list_address_groups_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( address_group.ListAddressGroupsResponse( @@ -1166,17 +1610,17 @@ def test_list_address_groups_pages(transport_name: str = "grpc"): address_group.AddressGroup(), address_group.AddressGroup(), ], - next_page_token='abc', + next_page_token="abc", ), address_group.ListAddressGroupsResponse( address_groups=[], - next_page_token='def', + next_page_token="def", ), address_group.ListAddressGroupsResponse( address_groups=[ address_group.AddressGroup(), ], - next_page_token='ghi', + next_page_token="ghi", ), address_group.ListAddressGroupsResponse( address_groups=[ @@ -1187,9 +1631,10 @@ def test_list_address_groups_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_address_groups(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token + @pytest.mark.asyncio async def test_list_address_groups_async_pager(): client = AddressGroupServiceAsyncClient( @@ -1198,8 +1643,10 @@ async def test_list_address_groups_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_address_groups), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( address_group.ListAddressGroupsResponse( @@ -1208,17 +1655,17 @@ async def test_list_address_groups_async_pager(): address_group.AddressGroup(), address_group.AddressGroup(), ], - next_page_token='abc', + next_page_token="abc", ), address_group.ListAddressGroupsResponse( address_groups=[], - next_page_token='def', + next_page_token="def", ), address_group.ListAddressGroupsResponse( address_groups=[ address_group.AddressGroup(), ], - next_page_token='ghi', + next_page_token="ghi", ), address_group.ListAddressGroupsResponse( address_groups=[ @@ -1228,15 +1675,16 @@ async def test_list_address_groups_async_pager(): ), RuntimeError, ) - async_pager = await client.list_address_groups(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_address_groups( + request={}, + ) + assert async_pager.next_page_token == "abc" responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, address_group.AddressGroup) - for i in responses) + assert all(isinstance(i, address_group.AddressGroup) for i in responses) @pytest.mark.asyncio @@ -1247,8 +1695,10 @@ async def test_list_address_groups_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_address_groups), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( address_group.ListAddressGroupsResponse( @@ -1257,17 +1707,17 @@ async def test_list_address_groups_async_pages(): address_group.AddressGroup(), address_group.AddressGroup(), ], - next_page_token='abc', + next_page_token="abc", ), address_group.ListAddressGroupsResponse( address_groups=[], - next_page_token='def', + next_page_token="def", ), address_group.ListAddressGroupsResponse( address_groups=[ address_group.AddressGroup(), ], - next_page_token='ghi', + next_page_token="ghi", ), address_group.ListAddressGroupsResponse( address_groups=[ @@ -1280,18 +1730,22 @@ async def test_list_address_groups_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_address_groups(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize("request_type", [ - address_group.GetAddressGroupRequest, - dict, -]) -def test_get_address_group(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + address_group.GetAddressGroupRequest, + dict, + ], +) +def test_get_address_group(request_type, transport: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1303,16 +1757,16 @@ def test_get_address_group(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.AddressGroup( - name='name_value', - description='description_value', + name="name_value", + description="description_value", type_=address_group.AddressGroup.Type.IPV4, - items=['items_value'], + items=["items_value"], capacity=846, - self_link='self_link_value', + self_link="self_link_value", purpose=[address_group.AddressGroup.Purpose.DEFAULT], ) response = client.get_address_group(request) @@ -1325,12 +1779,12 @@ def test_get_address_group(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, address_group.AddressGroup) - assert response.name == 'name_value' - assert response.description == 'description_value' + assert response.name == "name_value" + assert response.description == "description_value" assert response.type_ == address_group.AddressGroup.Type.IPV4 - assert response.items == ['items_value'] + assert response.items == ["items_value"] assert response.capacity == 846 - assert response.self_link == 'self_link_value' + assert response.self_link == "self_link_value" assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] @@ -1339,28 +1793,31 @@ def test_get_address_group_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = address_group.GetAddressGroupRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_address_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_address_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == address_group.GetAddressGroupRequest( - name='name_value', + name="name_value", ) + def test_get_address_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1379,8 +1836,12 @@ def test_get_address_group_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_address_group + ] = mock_rpc request = {} client.get_address_group(request) @@ -1393,8 +1854,11 @@ def test_get_address_group_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_address_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1408,12 +1872,17 @@ async def test_get_address_group_async_use_cached_wrapped_rpc(transport: str = " wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_address_group in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_address_group + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_address_group] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_address_group + ] = mock_rpc request = {} await client.get_address_group(request) @@ -1427,8 +1896,11 @@ async def test_get_address_group_async_use_cached_wrapped_rpc(transport: str = " assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_address_group_async(transport: str = 'grpc_asyncio', request_type=address_group.GetAddressGroupRequest): +async def test_get_address_group_async( + transport: str = "grpc_asyncio", request_type=address_group.GetAddressGroupRequest +): client = AddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1440,18 +1912,20 @@ async def test_get_address_group_async(transport: str = 'grpc_asyncio', request_ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup( - name='name_value', - description='description_value', - type_=address_group.AddressGroup.Type.IPV4, - items=['items_value'], - capacity=846, - self_link='self_link_value', - purpose=[address_group.AddressGroup.Purpose.DEFAULT], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.AddressGroup( + name="name_value", + description="description_value", + type_=address_group.AddressGroup.Type.IPV4, + items=["items_value"], + capacity=846, + self_link="self_link_value", + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + ) + ) response = await client.get_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1462,12 +1936,12 @@ async def test_get_address_group_async(transport: str = 'grpc_asyncio', request_ # Establish that the response is the type that we expect. assert isinstance(response, address_group.AddressGroup) - assert response.name == 'name_value' - assert response.description == 'description_value' + assert response.name == "name_value" + assert response.description == "description_value" assert response.type_ == address_group.AddressGroup.Type.IPV4 - assert response.items == ['items_value'] + assert response.items == ["items_value"] assert response.capacity == 846 - assert response.self_link == 'self_link_value' + assert response.self_link == "self_link_value" assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] @@ -1475,6 +1949,7 @@ async def test_get_address_group_async(transport: str = 'grpc_asyncio', request_ async def test_get_address_group_async_from_dict(): await test_get_address_group_async(request_type=dict) + def test_get_address_group_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1484,12 +1959,12 @@ def test_get_address_group_field_headers(): # a field header. Set these to a non-empty value. request = address_group.GetAddressGroupRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: call.return_value = address_group.AddressGroup() client.get_address_group(request) @@ -1501,9 +1976,9 @@ def test_get_address_group_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1516,13 +1991,15 @@ async def test_get_address_group_field_headers_async(): # a field header. Set these to a non-empty value. request = address_group.GetAddressGroupRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup()) + type(client.transport.get_address_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.AddressGroup() + ) await client.get_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1533,9 +2010,9 @@ async def test_get_address_group_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_address_group_flattened(): @@ -1545,14 +2022,14 @@ def test_get_address_group_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.AddressGroup() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_address_group( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1560,7 +2037,7 @@ def test_get_address_group_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -1574,9 +2051,10 @@ def test_get_address_group_flattened_error(): with pytest.raises(ValueError): client.get_address_group( address_group.GetAddressGroupRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_address_group_flattened_async(): client = AddressGroupServiceAsyncClient( @@ -1585,16 +2063,18 @@ async def test_get_address_group_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.AddressGroup() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.AddressGroup() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_address_group( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1602,9 +2082,10 @@ async def test_get_address_group_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_address_group_flattened_error_async(): client = AddressGroupServiceAsyncClient( @@ -1616,15 +2097,18 @@ async def test_get_address_group_flattened_error_async(): with pytest.raises(ValueError): await client.get_address_group( address_group.GetAddressGroupRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.CreateAddressGroupRequest, - dict, -]) -def test_create_address_group(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.CreateAddressGroupRequest, + dict, + ], +) +def test_create_address_group(request_type, transport: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1636,10 +2120,10 @@ def test_create_address_group(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.create_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1657,32 +2141,35 @@ def test_create_address_group_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.CreateAddressGroupRequest( - parent='parent_value', - address_group_id='address_group_id_value', - request_id='request_id_value', + parent="parent_value", + address_group_id="address_group_id_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.create_address_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_address_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.CreateAddressGroupRequest( - parent='parent_value', - address_group_id='address_group_id_value', - request_id='request_id_value', + parent="parent_value", + address_group_id="address_group_id_value", + request_id="request_id_value", ) + def test_create_address_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1697,12 +2184,18 @@ def test_create_address_group_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_address_group in client._transport._wrapped_methods + assert ( + client._transport.create_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_address_group + ] = mock_rpc request = {} client.create_address_group(request) @@ -1720,8 +2213,11 @@ def test_create_address_group_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_address_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1735,12 +2231,17 @@ async def test_create_address_group_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.create_address_group in client._client._transport._wrapped_methods + assert ( + client._client._transport.create_address_group + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_address_group] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.create_address_group + ] = mock_rpc request = {} await client.create_address_group(request) @@ -1759,8 +2260,12 @@ async def test_create_address_group_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_address_group_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.CreateAddressGroupRequest): +async def test_create_address_group_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.CreateAddressGroupRequest, +): client = AddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1772,11 +2277,11 @@ async def test_create_address_group_async(transport: str = 'grpc_asyncio', reque # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.create_address_group(request) @@ -1794,6 +2299,7 @@ async def test_create_address_group_async(transport: str = 'grpc_asyncio', reque async def test_create_address_group_async_from_dict(): await test_create_address_group_async(request_type=dict) + def test_create_address_group_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1803,13 +2309,13 @@ def test_create_address_group_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.CreateAddressGroupRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.create_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.create_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1820,9 +2326,9 @@ def test_create_address_group_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1835,13 +2341,15 @@ async def test_create_address_group_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.CreateAddressGroupRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.create_address_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.create_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1852,9 +2360,9 @@ async def test_create_address_group_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_create_address_group_flattened(): @@ -1864,16 +2372,16 @@ def test_create_address_group_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_address_group( - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) # Establish that the underlying call was made with the expected @@ -1881,13 +2389,13 @@ def test_create_address_group_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].address_group - mock_val = gcn_address_group.AddressGroup(name='name_value') + mock_val = gcn_address_group.AddressGroup(name="name_value") assert arg == mock_val arg = args[0].address_group_id - mock_val = 'address_group_id_value' + mock_val = "address_group_id_value" assert arg == mock_val @@ -1901,11 +2409,12 @@ def test_create_address_group_flattened_error(): with pytest.raises(ValueError): client.create_address_group( gcn_address_group.CreateAddressGroupRequest(), - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) + @pytest.mark.asyncio async def test_create_address_group_flattened_async(): client = AddressGroupServiceAsyncClient( @@ -1914,20 +2423,20 @@ async def test_create_address_group_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_address_group( - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) # Establish that the underlying call was made with the expected @@ -1935,15 +2444,16 @@ async def test_create_address_group_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].address_group - mock_val = gcn_address_group.AddressGroup(name='name_value') + mock_val = gcn_address_group.AddressGroup(name="name_value") assert arg == mock_val arg = args[0].address_group_id - mock_val = 'address_group_id_value' + mock_val = "address_group_id_value" assert arg == mock_val + @pytest.mark.asyncio async def test_create_address_group_flattened_error_async(): client = AddressGroupServiceAsyncClient( @@ -1955,17 +2465,20 @@ async def test_create_address_group_flattened_error_async(): with pytest.raises(ValueError): await client.create_address_group( gcn_address_group.CreateAddressGroupRequest(), - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.UpdateAddressGroupRequest, - dict, -]) -def test_update_address_group(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.UpdateAddressGroupRequest, + dict, + ], +) +def test_update_address_group(request_type, transport: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1977,10 +2490,10 @@ def test_update_address_group(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.update_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1998,28 +2511,31 @@ def test_update_address_group_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.UpdateAddressGroupRequest( - request_id='request_id_value', + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.update_address_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_address_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.UpdateAddressGroupRequest( - request_id='request_id_value', + request_id="request_id_value", ) + def test_update_address_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2034,12 +2550,18 @@ def test_update_address_group_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_address_group in client._transport._wrapped_methods + assert ( + client._transport.update_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_address_group + ] = mock_rpc request = {} client.update_address_group(request) @@ -2057,8 +2579,11 @@ def test_update_address_group_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_address_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2072,12 +2597,17 @@ async def test_update_address_group_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_address_group in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_address_group + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_address_group] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_address_group + ] = mock_rpc request = {} await client.update_address_group(request) @@ -2096,8 +2626,12 @@ async def test_update_address_group_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_address_group_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.UpdateAddressGroupRequest): +async def test_update_address_group_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.UpdateAddressGroupRequest, +): client = AddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2109,11 +2643,11 @@ async def test_update_address_group_async(transport: str = 'grpc_asyncio', reque # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.update_address_group(request) @@ -2131,6 +2665,7 @@ async def test_update_address_group_async(transport: str = 'grpc_asyncio', reque async def test_update_address_group_async_from_dict(): await test_update_address_group_async(request_type=dict) + def test_update_address_group_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2140,13 +2675,13 @@ def test_update_address_group_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.UpdateAddressGroupRequest() - request.address_group.name = 'name_value' + request.address_group.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.update_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.update_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -2157,9 +2692,9 @@ def test_update_address_group_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2172,13 +2707,15 @@ async def test_update_address_group_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.UpdateAddressGroupRequest() - request.address_group.name = 'name_value' + request.address_group.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.update_address_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.update_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -2189,9 +2726,9 @@ async def test_update_address_group_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group.name=name_value", + ) in kw["metadata"] def test_update_address_group_flattened(): @@ -2201,15 +2738,15 @@ def test_update_address_group_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_address_group( - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -2217,10 +2754,10 @@ def test_update_address_group_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = gcn_address_group.AddressGroup(name='name_value') + mock_val = gcn_address_group.AddressGroup(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -2234,10 +2771,11 @@ def test_update_address_group_flattened_error(): with pytest.raises(ValueError): client.update_address_group( gcn_address_group.UpdateAddressGroupRequest(), - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_address_group_flattened_async(): client = AddressGroupServiceAsyncClient( @@ -2246,19 +2784,19 @@ async def test_update_address_group_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_address_group( - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -2266,12 +2804,13 @@ async def test_update_address_group_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = gcn_address_group.AddressGroup(name='name_value') + mock_val = gcn_address_group.AddressGroup(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_address_group_flattened_error_async(): client = AddressGroupServiceAsyncClient( @@ -2283,16 +2822,19 @@ async def test_update_address_group_flattened_error_async(): with pytest.raises(ValueError): await client.update_address_group( gcn_address_group.UpdateAddressGroupRequest(), - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.AddAddressGroupItemsRequest, - dict, -]) -def test_add_address_group_items(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.AddAddressGroupItemsRequest, + dict, + ], +) +def test_add_address_group_items(request_type, transport: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2304,10 +2846,10 @@ def test_add_address_group_items(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.add_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2325,30 +2867,33 @@ def test_add_address_group_items_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.AddAddressGroupItemsRequest( - address_group='address_group_value', - request_id='request_id_value', + address_group="address_group_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.add_address_group_items), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.add_address_group_items(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.AddAddressGroupItemsRequest( - address_group='address_group_value', - request_id='request_id_value', + address_group="address_group_value", + request_id="request_id_value", ) + def test_add_address_group_items_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2363,12 +2908,19 @@ def test_add_address_group_items_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.add_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.add_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.add_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.add_address_group_items + ] = mock_rpc request = {} client.add_address_group_items(request) @@ -2386,8 +2938,11 @@ def test_add_address_group_items_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_add_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_add_address_group_items_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2401,12 +2956,17 @@ async def test_add_address_group_items_async_use_cached_wrapped_rpc(transport: s wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.add_address_group_items in client._client._transport._wrapped_methods + assert ( + client._client._transport.add_address_group_items + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.add_address_group_items] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.add_address_group_items + ] = mock_rpc request = {} await client.add_address_group_items(request) @@ -2425,8 +2985,12 @@ async def test_add_address_group_items_async_use_cached_wrapped_rpc(transport: s assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_add_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.AddAddressGroupItemsRequest): +async def test_add_address_group_items_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.AddAddressGroupItemsRequest, +): client = AddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2438,11 +3002,11 @@ async def test_add_address_group_items_async(transport: str = 'grpc_asyncio', re # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.add_address_group_items(request) @@ -2460,6 +3024,7 @@ async def test_add_address_group_items_async(transport: str = 'grpc_asyncio', re async def test_add_address_group_items_async_from_dict(): await test_add_address_group_items_async(request_type=dict) + def test_add_address_group_items_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2469,13 +3034,13 @@ def test_add_address_group_items_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.AddAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.add_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.add_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2486,9 +3051,9 @@ def test_add_address_group_items_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2501,13 +3066,15 @@ async def test_add_address_group_items_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.AddAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.add_address_group_items), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.add_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2518,9 +3085,9 @@ async def test_add_address_group_items_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] def test_add_address_group_items_flattened(): @@ -2530,15 +3097,15 @@ def test_add_address_group_items_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.add_address_group_items( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) # Establish that the underlying call was made with the expected @@ -2546,10 +3113,10 @@ def test_add_address_group_items_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].items - mock_val = ['items_value'] + mock_val = ["items_value"] assert arg == mock_val @@ -2563,10 +3130,11 @@ def test_add_address_group_items_flattened_error(): with pytest.raises(ValueError): client.add_address_group_items( gcn_address_group.AddAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) + @pytest.mark.asyncio async def test_add_address_group_items_flattened_async(): client = AddressGroupServiceAsyncClient( @@ -2575,19 +3143,19 @@ async def test_add_address_group_items_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.add_address_group_items( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) # Establish that the underlying call was made with the expected @@ -2595,12 +3163,13 @@ async def test_add_address_group_items_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].items - mock_val = ['items_value'] + mock_val = ["items_value"] assert arg == mock_val + @pytest.mark.asyncio async def test_add_address_group_items_flattened_error_async(): client = AddressGroupServiceAsyncClient( @@ -2612,16 +3181,19 @@ async def test_add_address_group_items_flattened_error_async(): with pytest.raises(ValueError): await client.add_address_group_items( gcn_address_group.AddAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.RemoveAddressGroupItemsRequest, - dict, -]) -def test_remove_address_group_items(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.RemoveAddressGroupItemsRequest, + dict, + ], +) +def test_remove_address_group_items(request_type, transport: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2633,10 +3205,10 @@ def test_remove_address_group_items(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.remove_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2654,30 +3226,33 @@ def test_remove_address_group_items_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.RemoveAddressGroupItemsRequest( - address_group='address_group_value', - request_id='request_id_value', + address_group="address_group_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.remove_address_group_items), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.remove_address_group_items(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.RemoveAddressGroupItemsRequest( - address_group='address_group_value', - request_id='request_id_value', + address_group="address_group_value", + request_id="request_id_value", ) + def test_remove_address_group_items_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2692,12 +3267,19 @@ def test_remove_address_group_items_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.remove_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.remove_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.remove_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.remove_address_group_items + ] = mock_rpc request = {} client.remove_address_group_items(request) @@ -2715,8 +3297,11 @@ def test_remove_address_group_items_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_remove_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_remove_address_group_items_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2730,12 +3315,17 @@ async def test_remove_address_group_items_async_use_cached_wrapped_rpc(transport wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.remove_address_group_items in client._client._transport._wrapped_methods + assert ( + client._client._transport.remove_address_group_items + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.remove_address_group_items] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.remove_address_group_items + ] = mock_rpc request = {} await client.remove_address_group_items(request) @@ -2754,8 +3344,12 @@ async def test_remove_address_group_items_async_use_cached_wrapped_rpc(transport assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_remove_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.RemoveAddressGroupItemsRequest): +async def test_remove_address_group_items_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.RemoveAddressGroupItemsRequest, +): client = AddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2767,11 +3361,11 @@ async def test_remove_address_group_items_async(transport: str = 'grpc_asyncio', # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.remove_address_group_items(request) @@ -2789,6 +3383,7 @@ async def test_remove_address_group_items_async(transport: str = 'grpc_asyncio', async def test_remove_address_group_items_async_from_dict(): await test_remove_address_group_items_async(request_type=dict) + def test_remove_address_group_items_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2798,13 +3393,13 @@ def test_remove_address_group_items_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.RemoveAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.remove_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.remove_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2815,9 +3410,9 @@ def test_remove_address_group_items_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2830,13 +3425,15 @@ async def test_remove_address_group_items_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.RemoveAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.remove_address_group_items), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.remove_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2847,9 +3444,9 @@ async def test_remove_address_group_items_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] def test_remove_address_group_items_flattened(): @@ -2859,15 +3456,15 @@ def test_remove_address_group_items_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.remove_address_group_items( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) # Establish that the underlying call was made with the expected @@ -2875,10 +3472,10 @@ def test_remove_address_group_items_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].items - mock_val = ['items_value'] + mock_val = ["items_value"] assert arg == mock_val @@ -2892,10 +3489,11 @@ def test_remove_address_group_items_flattened_error(): with pytest.raises(ValueError): client.remove_address_group_items( gcn_address_group.RemoveAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) + @pytest.mark.asyncio async def test_remove_address_group_items_flattened_async(): client = AddressGroupServiceAsyncClient( @@ -2904,19 +3502,19 @@ async def test_remove_address_group_items_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.remove_address_group_items( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) # Establish that the underlying call was made with the expected @@ -2924,12 +3522,13 @@ async def test_remove_address_group_items_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].items - mock_val = ['items_value'] + mock_val = ["items_value"] assert arg == mock_val + @pytest.mark.asyncio async def test_remove_address_group_items_flattened_error_async(): client = AddressGroupServiceAsyncClient( @@ -2941,16 +3540,19 @@ async def test_remove_address_group_items_flattened_error_async(): with pytest.raises(ValueError): await client.remove_address_group_items( gcn_address_group.RemoveAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.CloneAddressGroupItemsRequest, - dict, -]) -def test_clone_address_group_items(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.CloneAddressGroupItemsRequest, + dict, + ], +) +def test_clone_address_group_items(request_type, transport: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2962,10 +3564,10 @@ def test_clone_address_group_items(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.clone_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2983,32 +3585,35 @@ def test_clone_address_group_items_non_empty_request_with_auto_populated_field() # automatically populated, according to AIP-4235, with non-empty requests. client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.CloneAddressGroupItemsRequest( - address_group='address_group_value', - source_address_group='source_address_group_value', - request_id='request_id_value', + address_group="address_group_value", + source_address_group="source_address_group_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.clone_address_group_items), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.clone_address_group_items(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.CloneAddressGroupItemsRequest( - address_group='address_group_value', - source_address_group='source_address_group_value', - request_id='request_id_value', + address_group="address_group_value", + source_address_group="source_address_group_value", + request_id="request_id_value", ) + def test_clone_address_group_items_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3023,12 +3628,19 @@ def test_clone_address_group_items_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.clone_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.clone_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.clone_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.clone_address_group_items + ] = mock_rpc request = {} client.clone_address_group_items(request) @@ -3046,8 +3658,11 @@ def test_clone_address_group_items_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_clone_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_clone_address_group_items_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3061,12 +3676,17 @@ async def test_clone_address_group_items_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.clone_address_group_items in client._client._transport._wrapped_methods + assert ( + client._client._transport.clone_address_group_items + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.clone_address_group_items] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.clone_address_group_items + ] = mock_rpc request = {} await client.clone_address_group_items(request) @@ -3085,8 +3705,12 @@ async def test_clone_address_group_items_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_clone_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.CloneAddressGroupItemsRequest): +async def test_clone_address_group_items_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.CloneAddressGroupItemsRequest, +): client = AddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3098,11 +3722,11 @@ async def test_clone_address_group_items_async(transport: str = 'grpc_asyncio', # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.clone_address_group_items(request) @@ -3120,6 +3744,7 @@ async def test_clone_address_group_items_async(transport: str = 'grpc_asyncio', async def test_clone_address_group_items_async_from_dict(): await test_clone_address_group_items_async(request_type=dict) + def test_clone_address_group_items_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3129,13 +3754,13 @@ def test_clone_address_group_items_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.CloneAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.clone_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.clone_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -3146,9 +3771,9 @@ def test_clone_address_group_items_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -3161,13 +3786,15 @@ async def test_clone_address_group_items_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.CloneAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.clone_address_group_items), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.clone_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -3178,9 +3805,9 @@ async def test_clone_address_group_items_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] def test_clone_address_group_items_flattened(): @@ -3190,15 +3817,15 @@ def test_clone_address_group_items_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.clone_address_group_items( - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) # Establish that the underlying call was made with the expected @@ -3206,10 +3833,10 @@ def test_clone_address_group_items_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].source_address_group - mock_val = 'source_address_group_value' + mock_val = "source_address_group_value" assert arg == mock_val @@ -3223,10 +3850,11 @@ def test_clone_address_group_items_flattened_error(): with pytest.raises(ValueError): client.clone_address_group_items( gcn_address_group.CloneAddressGroupItemsRequest(), - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) + @pytest.mark.asyncio async def test_clone_address_group_items_flattened_async(): client = AddressGroupServiceAsyncClient( @@ -3235,19 +3863,19 @@ async def test_clone_address_group_items_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.clone_address_group_items( - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) # Establish that the underlying call was made with the expected @@ -3255,12 +3883,13 @@ async def test_clone_address_group_items_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].source_address_group - mock_val = 'source_address_group_value' + mock_val = "source_address_group_value" assert arg == mock_val + @pytest.mark.asyncio async def test_clone_address_group_items_flattened_error_async(): client = AddressGroupServiceAsyncClient( @@ -3272,16 +3901,19 @@ async def test_clone_address_group_items_flattened_error_async(): with pytest.raises(ValueError): await client.clone_address_group_items( gcn_address_group.CloneAddressGroupItemsRequest(), - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) -@pytest.mark.parametrize("request_type", [ - address_group.DeleteAddressGroupRequest, - dict, -]) -def test_delete_address_group(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + address_group.DeleteAddressGroupRequest, + dict, + ], +) +def test_delete_address_group(request_type, transport: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3293,10 +3925,10 @@ def test_delete_address_group(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.delete_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -3314,30 +3946,33 @@ def test_delete_address_group_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = address_group.DeleteAddressGroupRequest( - name='name_value', - request_id='request_id_value', + name="name_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.delete_address_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.delete_address_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == address_group.DeleteAddressGroupRequest( - name='name_value', - request_id='request_id_value', + name="name_value", + request_id="request_id_value", ) + def test_delete_address_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3352,12 +3987,18 @@ def test_delete_address_group_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_address_group in client._transport._wrapped_methods + assert ( + client._transport.delete_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_address_group + ] = mock_rpc request = {} client.delete_address_group(request) @@ -3375,8 +4016,11 @@ def test_delete_address_group_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_address_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3390,12 +4034,17 @@ async def test_delete_address_group_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.delete_address_group in client._client._transport._wrapped_methods + assert ( + client._client._transport.delete_address_group + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_address_group] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.delete_address_group + ] = mock_rpc request = {} await client.delete_address_group(request) @@ -3414,8 +4063,12 @@ async def test_delete_address_group_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_address_group_async(transport: str = 'grpc_asyncio', request_type=address_group.DeleteAddressGroupRequest): +async def test_delete_address_group_async( + transport: str = "grpc_asyncio", + request_type=address_group.DeleteAddressGroupRequest, +): client = AddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3427,11 +4080,11 @@ async def test_delete_address_group_async(transport: str = 'grpc_asyncio', reque # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.delete_address_group(request) @@ -3449,6 +4102,7 @@ async def test_delete_address_group_async(transport: str = 'grpc_asyncio', reque async def test_delete_address_group_async_from_dict(): await test_delete_address_group_async(request_type=dict) + def test_delete_address_group_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3458,13 +4112,13 @@ def test_delete_address_group_field_headers(): # a field header. Set these to a non-empty value. request = address_group.DeleteAddressGroupRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.delete_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.delete_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -3475,9 +4129,9 @@ def test_delete_address_group_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -3490,13 +4144,15 @@ async def test_delete_address_group_field_headers_async(): # a field header. Set these to a non-empty value. request = address_group.DeleteAddressGroupRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.delete_address_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.delete_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -3507,9 +4163,9 @@ async def test_delete_address_group_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_delete_address_group_flattened(): @@ -3519,14 +4175,14 @@ def test_delete_address_group_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_address_group( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -3534,7 +4190,7 @@ def test_delete_address_group_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -3548,9 +4204,10 @@ def test_delete_address_group_flattened_error(): with pytest.raises(ValueError): client.delete_address_group( address_group.DeleteAddressGroupRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_address_group_flattened_async(): client = AddressGroupServiceAsyncClient( @@ -3559,18 +4216,18 @@ async def test_delete_address_group_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_address_group( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -3578,9 +4235,10 @@ async def test_delete_address_group_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_delete_address_group_flattened_error_async(): client = AddressGroupServiceAsyncClient( @@ -3592,15 +4250,18 @@ async def test_delete_address_group_flattened_error_async(): with pytest.raises(ValueError): await client.delete_address_group( address_group.DeleteAddressGroupRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.ListAddressGroupReferencesRequest, - dict, -]) -def test_list_address_group_references(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.ListAddressGroupReferencesRequest, + dict, + ], +) +def test_list_address_group_references(request_type, transport: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3612,11 +4273,11 @@ def test_list_address_group_references(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gcn_address_group.ListAddressGroupReferencesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_address_group_references(request) @@ -3628,7 +4289,7 @@ def test_list_address_group_references(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupReferencesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_address_group_references_non_empty_request_with_auto_populated_field(): @@ -3636,30 +4297,33 @@ def test_list_address_group_references_non_empty_request_with_auto_populated_fie # automatically populated, according to AIP-4235, with non-empty requests. client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.ListAddressGroupReferencesRequest( - address_group='address_group_value', - page_token='page_token_value', + address_group="address_group_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_address_group_references), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_address_group_references(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.ListAddressGroupReferencesRequest( - address_group='address_group_value', - page_token='page_token_value', + address_group="address_group_value", + page_token="page_token_value", ) + def test_list_address_group_references_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3674,12 +4338,19 @@ def test_list_address_group_references_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_address_group_references in client._transport._wrapped_methods + assert ( + client._transport.list_address_group_references + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_address_group_references] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_address_group_references + ] = mock_rpc request = {} client.list_address_group_references(request) @@ -3692,8 +4363,11 @@ def test_list_address_group_references_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_address_group_references_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_address_group_references_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3707,12 +4381,17 @@ async def test_list_address_group_references_async_use_cached_wrapped_rpc(transp wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_address_group_references in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_address_group_references + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_address_group_references] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_address_group_references + ] = mock_rpc request = {} await client.list_address_group_references(request) @@ -3726,8 +4405,12 @@ async def test_list_address_group_references_async_use_cached_wrapped_rpc(transp assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_address_group_references_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.ListAddressGroupReferencesRequest): +async def test_list_address_group_references_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.ListAddressGroupReferencesRequest, +): client = AddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3739,12 +4422,14 @@ async def test_list_address_group_references_async(transport: str = 'grpc_asynci # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_address_group_references(request) # Establish that the underlying gRPC stub method was called. @@ -3755,13 +4440,14 @@ async def test_list_address_group_references_async(transport: str = 'grpc_asynci # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupReferencesAsyncPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio async def test_list_address_group_references_async_from_dict(): await test_list_address_group_references_async(request_type=dict) + def test_list_address_group_references_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3771,12 +4457,12 @@ def test_list_address_group_references_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.ListAddressGroupReferencesRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() client.list_address_group_references(request) @@ -3788,9 +4474,9 @@ def test_list_address_group_references_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -3803,13 +4489,15 @@ async def test_list_address_group_references_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.ListAddressGroupReferencesRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse()) + type(client.transport.list_address_group_references), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcn_address_group.ListAddressGroupReferencesResponse() + ) await client.list_address_group_references(request) # Establish that the underlying gRPC stub method was called. @@ -3820,9 +4508,9 @@ async def test_list_address_group_references_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] def test_list_address_group_references_flattened(): @@ -3832,14 +4520,14 @@ def test_list_address_group_references_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_address_group_references( - address_group='address_group_value', + address_group="address_group_value", ) # Establish that the underlying call was made with the expected @@ -3847,7 +4535,7 @@ def test_list_address_group_references_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val @@ -3861,9 +4549,10 @@ def test_list_address_group_references_flattened_error(): with pytest.raises(ValueError): client.list_address_group_references( gcn_address_group.ListAddressGroupReferencesRequest(), - address_group='address_group_value', + address_group="address_group_value", ) + @pytest.mark.asyncio async def test_list_address_group_references_flattened_async(): client = AddressGroupServiceAsyncClient( @@ -3872,16 +4561,18 @@ async def test_list_address_group_references_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcn_address_group.ListAddressGroupReferencesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_address_group_references( - address_group='address_group_value', + address_group="address_group_value", ) # Establish that the underlying call was made with the expected @@ -3889,9 +4580,10 @@ async def test_list_address_group_references_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val + @pytest.mark.asyncio async def test_list_address_group_references_flattened_error_async(): client = AddressGroupServiceAsyncClient( @@ -3903,7 +4595,7 @@ async def test_list_address_group_references_flattened_error_async(): with pytest.raises(ValueError): await client.list_address_group_references( gcn_address_group.ListAddressGroupReferencesRequest(), - address_group='address_group_value', + address_group="address_group_value", ) @@ -3915,8 +4607,8 @@ def test_list_address_group_references_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( gcn_address_group.ListAddressGroupReferencesResponse( @@ -3925,17 +4617,17 @@ def test_list_address_group_references_pager(transport_name: str = "grpc"): gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='abc', + next_page_token="abc", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[], - next_page_token='def', + next_page_token="def", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='ghi', + next_page_token="ghi", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ @@ -3950,11 +4642,11 @@ def test_list_address_group_references_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('address_group', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("address_group", ""),)), + ) + pager = client.list_address_group_references( + request={}, retry=retry, timeout=timeout ) - pager = client.list_address_group_references(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -3962,8 +4654,15 @@ def test_list_address_group_references_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) - for i in results) + assert all( + isinstance( + i, + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference, + ) + for i in results + ) + + def test_list_address_group_references_pages(transport_name: str = "grpc"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3972,8 +4671,8 @@ def test_list_address_group_references_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( gcn_address_group.ListAddressGroupReferencesResponse( @@ -3982,17 +4681,17 @@ def test_list_address_group_references_pages(transport_name: str = "grpc"): gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='abc', + next_page_token="abc", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[], - next_page_token='def', + next_page_token="def", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='ghi', + next_page_token="ghi", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ @@ -4003,9 +4702,10 @@ def test_list_address_group_references_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_address_group_references(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token + @pytest.mark.asyncio async def test_list_address_group_references_async_pager(): client = AddressGroupServiceAsyncClient( @@ -4014,8 +4714,10 @@ async def test_list_address_group_references_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_address_group_references), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( gcn_address_group.ListAddressGroupReferencesResponse( @@ -4024,17 +4726,17 @@ async def test_list_address_group_references_async_pager(): gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='abc', + next_page_token="abc", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[], - next_page_token='def', + next_page_token="def", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='ghi', + next_page_token="ghi", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ @@ -4044,15 +4746,22 @@ async def test_list_address_group_references_async_pager(): ), RuntimeError, ) - async_pager = await client.list_address_group_references(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_address_group_references( + request={}, + ) + assert async_pager.next_page_token == "abc" responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) - for i in responses) + assert all( + isinstance( + i, + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference, + ) + for i in responses + ) @pytest.mark.asyncio @@ -4063,8 +4772,10 @@ async def test_list_address_group_references_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_address_group_references), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( gcn_address_group.ListAddressGroupReferencesResponse( @@ -4073,17 +4784,17 @@ async def test_list_address_group_references_async_pages(): gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='abc', + next_page_token="abc", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[], - next_page_token='def', + next_page_token="def", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='ghi', + next_page_token="ghi", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ @@ -4096,11 +4807,11 @@ async def test_list_address_group_references_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_address_group_references(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -4118,12 +4829,18 @@ def test_list_address_groups_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_address_groups in client._transport._wrapped_methods + assert ( + client._transport.list_address_groups in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_address_groups] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_address_groups + ] = mock_rpc request = {} client.list_address_groups(request) @@ -4138,57 +4855,68 @@ def test_list_address_groups_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_address_groups_rest_required_fields(request_type=address_group.ListAddressGroupsRequest): +def test_list_address_groups_rest_required_fields( + request_type=address_group.ListAddressGroupsRequest, +): transport_class = transports.AddressGroupServiceRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_groups._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_address_groups._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = 'parent_value' + jsonified_request["parent"] = "parent_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_groups._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_address_groups._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", "return_partial_success", )) + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + "return_partial_success", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' + assert jsonified_request["parent"] == "parent_value" client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = address_group.ListAddressGroupsResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -4199,24 +4927,33 @@ def test_list_address_groups_rest_required_fields(request_type=address_group.Lis return_value = address_group.ListAddressGroupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_address_groups(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_address_groups_rest_unset_required_fields(): - transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_address_groups._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "returnPartialSuccess", )) & set(("parent", ))) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("parent",)) + ) def test_list_address_groups_rest_flattened(): @@ -4226,16 +4963,16 @@ def test_list_address_groups_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = address_group.ListAddressGroupsResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -4245,7 +4982,7 @@ def test_list_address_groups_rest_flattened(): # Convert return value to protobuf type return_value = address_group.ListAddressGroupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4255,10 +4992,14 @@ def test_list_address_groups_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/addressGroups" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/addressGroups" + % client.transport._host, + args[1], + ) -def test_list_address_groups_rest_flattened_error(transport: str = 'rest'): +def test_list_address_groups_rest_flattened_error(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4269,20 +5010,20 @@ def test_list_address_groups_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_address_groups( address_group.ListAddressGroupsRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_address_groups_rest_pager(transport: str = 'rest'): +def test_list_address_groups_rest_pager(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: + # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( address_group.ListAddressGroupsResponse( @@ -4291,17 +5032,17 @@ def test_list_address_groups_rest_pager(transport: str = 'rest'): address_group.AddressGroup(), address_group.AddressGroup(), ], - next_page_token='abc', + next_page_token="abc", ), address_group.ListAddressGroupsResponse( address_groups=[], - next_page_token='def', + next_page_token="def", ), address_group.ListAddressGroupsResponse( address_groups=[ address_group.AddressGroup(), ], - next_page_token='ghi', + next_page_token="ghi", ), address_group.ListAddressGroupsResponse( address_groups=[ @@ -4314,24 +5055,25 @@ def test_list_address_groups_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(address_group.ListAddressGroupsResponse.to_json(x) for x in response) + response = tuple( + address_group.ListAddressGroupsResponse.to_json(x) for x in response + ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') + return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {'parent': 'projects/sample1/locations/sample2'} + sample_request = {"parent": "projects/sample1/locations/sample2"} pager = client.list_address_groups(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, address_group.AddressGroup) - for i in results) + assert all(isinstance(i, address_group.AddressGroup) for i in results) pages = list(client.list_address_groups(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -4353,8 +5095,12 @@ def test_get_address_group_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_address_group + ] = mock_rpc request = {} client.get_address_group(request) @@ -4369,55 +5115,60 @@ def test_get_address_group_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_address_group_rest_required_fields(request_type=address_group.GetAddressGroupRequest): +def test_get_address_group_rest_required_fields( + request_type=address_group.GetAddressGroupRequest, +): transport_class = transports.AddressGroupServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_address_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_address_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = address_group.AddressGroup() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -4428,24 +5179,24 @@ def test_get_address_group_rest_required_fields(request_type=address_group.GetAd return_value = address_group.AddressGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_address_group(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_address_group_rest_unset_required_fields(): - transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_address_group._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_address_group_rest_flattened(): @@ -4455,16 +5206,18 @@ def test_get_address_group_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = address_group.AddressGroup() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "name": "projects/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -4474,7 +5227,7 @@ def test_get_address_group_rest_flattened(): # Convert return value to protobuf type return_value = address_group.AddressGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4484,10 +5237,14 @@ def test_get_address_group_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/addressGroups/*}" + % client.transport._host, + args[1], + ) -def test_get_address_group_rest_flattened_error(transport: str = 'rest'): +def test_get_address_group_rest_flattened_error(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4498,7 +5255,7 @@ def test_get_address_group_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_address_group( address_group.GetAddressGroupRequest(), - name='name_value', + name="name_value", ) @@ -4516,12 +5273,18 @@ def test_create_address_group_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_address_group in client._transport._wrapped_methods + assert ( + client._transport.create_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_address_group + ] = mock_rpc request = {} client.create_address_group(request) @@ -4540,7 +5303,9 @@ def test_create_address_group_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_address_group_rest_required_fields(request_type=gcn_address_group.CreateAddressGroupRequest): +def test_create_address_group_rest_required_fields( + request_type=gcn_address_group.CreateAddressGroupRequest, +): transport_class = transports.AddressGroupServiceRestTransport request_init = {} @@ -4548,65 +5313,73 @@ def test_create_address_group_rest_required_fields(request_type=gcn_address_grou request_init["address_group_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped assert "addressGroupId" not in jsonified_request - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_address_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present assert "addressGroupId" in jsonified_request assert jsonified_request["addressGroupId"] == request_init["address_group_id"] - jsonified_request["parent"] = 'parent_value' - jsonified_request["addressGroupId"] = 'address_group_id_value' + jsonified_request["parent"] = "parent_value" + jsonified_request["addressGroupId"] = "address_group_id_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_address_group._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("address_group_id", "request_id", )) + assert not set(unset_fields) - set( + ( + "address_group_id", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' + assert jsonified_request["parent"] == "parent_value" assert "addressGroupId" in jsonified_request - assert jsonified_request["addressGroupId"] == 'address_group_id_value' + assert jsonified_request["addressGroupId"] == "address_group_id_value" client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4617,17 +5390,33 @@ def test_create_address_group_rest_required_fields(request_type=gcn_address_grou "addressGroupId", "", ), - ('$alt', 'json;enum-encoding=int') + ("$alt", "json;enum-encoding=int"), ] - actual_params = req.call_args.kwargs['params'] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_create_address_group_rest_unset_required_fields(): - transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.create_address_group._get_unset_required_fields({}) - assert set(unset_fields) == (set(("addressGroupId", "requestId", )) & set(("parent", "addressGroupId", "addressGroup", ))) + assert set(unset_fields) == ( + set( + ( + "addressGroupId", + "requestId", + ) + ) + & set( + ( + "parent", + "addressGroupId", + "addressGroup", + ) + ) + ) def test_create_address_group_rest_flattened(): @@ -4637,18 +5426,18 @@ def test_create_address_group_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) mock_args.update(sample_request) @@ -4656,7 +5445,7 @@ def test_create_address_group_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4666,10 +5455,14 @@ def test_create_address_group_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/addressGroups" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/addressGroups" + % client.transport._host, + args[1], + ) -def test_create_address_group_rest_flattened_error(transport: str = 'rest'): +def test_create_address_group_rest_flattened_error(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4680,9 +5473,9 @@ def test_create_address_group_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.create_address_group( gcn_address_group.CreateAddressGroupRequest(), - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) @@ -4700,12 +5493,18 @@ def test_update_address_group_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_address_group in client._transport._wrapped_methods + assert ( + client._transport.update_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_address_group + ] = mock_rpc request = {} client.update_address_group(request) @@ -4724,78 +5523,96 @@ def test_update_address_group_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_address_group_rest_required_fields(request_type=gcn_address_group.UpdateAddressGroupRequest): +def test_update_address_group_rest_required_fields( + request_type=gcn_address_group.UpdateAddressGroupRequest, +): transport_class = transports.AddressGroupServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_address_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_address_group._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", "update_mask", )) + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_address_group(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_address_group_rest_unset_required_fields(): - transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_address_group._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("addressGroup", ))) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set(("addressGroup",)) + ) def test_update_address_group_rest_flattened(): @@ -4805,17 +5622,21 @@ def test_update_address_group_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'address_group': {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'}} + sample_request = { + "address_group": { + "name": "projects/sample1/locations/sample2/addressGroups/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -4823,7 +5644,7 @@ def test_update_address_group_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4833,10 +5654,14 @@ def test_update_address_group_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{address_group.name=projects/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{address_group.name=projects/*/locations/*/addressGroups/*}" + % client.transport._host, + args[1], + ) -def test_update_address_group_rest_flattened_error(transport: str = 'rest'): +def test_update_address_group_rest_flattened_error(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4847,8 +5672,8 @@ def test_update_address_group_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_address_group( gcn_address_group.UpdateAddressGroupRequest(), - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -4866,12 +5691,19 @@ def test_add_address_group_items_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.add_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.add_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.add_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.add_address_group_items + ] = mock_rpc request = {} client.add_address_group_items(request) @@ -4890,7 +5722,9 @@ def test_add_address_group_items_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_add_address_group_items_rest_required_fields(request_type=gcn_address_group.AddAddressGroupItemsRequest): +def test_add_address_group_items_rest_required_fields( + request_type=gcn_address_group.AddAddressGroupItemsRequest, +): transport_class = transports.AddressGroupServiceRestTransport request_init = {} @@ -4898,77 +5732,88 @@ def test_add_address_group_items_rest_required_fields(request_type=gcn_address_g request_init["items"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["addressGroup"] = 'address_group_value' - jsonified_request["items"] = 'items_value' + jsonified_request["addressGroup"] = "address_group_value" + jsonified_request["items"] = "items_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "addressGroup" in jsonified_request - assert jsonified_request["addressGroup"] == 'address_group_value' + assert jsonified_request["addressGroup"] == "address_group_value" assert "items" in jsonified_request - assert jsonified_request["items"] == 'items_value' + assert jsonified_request["items"] == "items_value" client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.add_address_group_items(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_add_address_group_items_rest_unset_required_fields(): - transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.add_address_group_items._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("addressGroup", "items", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "addressGroup", + "items", + ) + ) + ) def test_add_address_group_items_rest_flattened(): @@ -4978,17 +5823,19 @@ def test_add_address_group_items_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) mock_args.update(sample_request) @@ -4996,7 +5843,7 @@ def test_add_address_group_items_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -5006,10 +5853,14 @@ def test_add_address_group_items_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:addItems" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:addItems" + % client.transport._host, + args[1], + ) -def test_add_address_group_items_rest_flattened_error(transport: str = 'rest'): +def test_add_address_group_items_rest_flattened_error(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5020,8 +5871,8 @@ def test_add_address_group_items_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.add_address_group_items( gcn_address_group.AddAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) @@ -5039,12 +5890,19 @@ def test_remove_address_group_items_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.remove_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.remove_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.remove_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.remove_address_group_items + ] = mock_rpc request = {} client.remove_address_group_items(request) @@ -5063,7 +5921,9 @@ def test_remove_address_group_items_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_remove_address_group_items_rest_required_fields(request_type=gcn_address_group.RemoveAddressGroupItemsRequest): +def test_remove_address_group_items_rest_required_fields( + request_type=gcn_address_group.RemoveAddressGroupItemsRequest, +): transport_class = transports.AddressGroupServiceRestTransport request_init = {} @@ -5071,77 +5931,88 @@ def test_remove_address_group_items_rest_required_fields(request_type=gcn_addres request_init["items"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["addressGroup"] = 'address_group_value' - jsonified_request["items"] = 'items_value' + jsonified_request["addressGroup"] = "address_group_value" + jsonified_request["items"] = "items_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "addressGroup" in jsonified_request - assert jsonified_request["addressGroup"] == 'address_group_value' + assert jsonified_request["addressGroup"] == "address_group_value" assert "items" in jsonified_request - assert jsonified_request["items"] == 'items_value' + assert jsonified_request["items"] == "items_value" client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.remove_address_group_items(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_remove_address_group_items_rest_unset_required_fields(): - transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.remove_address_group_items._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("addressGroup", "items", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "addressGroup", + "items", + ) + ) + ) def test_remove_address_group_items_rest_flattened(): @@ -5151,17 +6022,19 @@ def test_remove_address_group_items_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) mock_args.update(sample_request) @@ -5169,7 +6042,7 @@ def test_remove_address_group_items_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -5179,10 +6052,14 @@ def test_remove_address_group_items_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:removeItems" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:removeItems" + % client.transport._host, + args[1], + ) -def test_remove_address_group_items_rest_flattened_error(transport: str = 'rest'): +def test_remove_address_group_items_rest_flattened_error(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5193,8 +6070,8 @@ def test_remove_address_group_items_rest_flattened_error(transport: str = 'rest' with pytest.raises(ValueError): client.remove_address_group_items( gcn_address_group.RemoveAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) @@ -5212,12 +6089,19 @@ def test_clone_address_group_items_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.clone_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.clone_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.clone_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.clone_address_group_items + ] = mock_rpc request = {} client.clone_address_group_items(request) @@ -5236,7 +6120,9 @@ def test_clone_address_group_items_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_clone_address_group_items_rest_required_fields(request_type=gcn_address_group.CloneAddressGroupItemsRequest): +def test_clone_address_group_items_rest_required_fields( + request_type=gcn_address_group.CloneAddressGroupItemsRequest, +): transport_class = transports.AddressGroupServiceRestTransport request_init = {} @@ -5244,77 +6130,88 @@ def test_clone_address_group_items_rest_required_fields(request_type=gcn_address request_init["source_address_group"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clone_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).clone_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["addressGroup"] = 'address_group_value' - jsonified_request["sourceAddressGroup"] = 'source_address_group_value' + jsonified_request["addressGroup"] = "address_group_value" + jsonified_request["sourceAddressGroup"] = "source_address_group_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clone_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).clone_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "addressGroup" in jsonified_request - assert jsonified_request["addressGroup"] == 'address_group_value' + assert jsonified_request["addressGroup"] == "address_group_value" assert "sourceAddressGroup" in jsonified_request - assert jsonified_request["sourceAddressGroup"] == 'source_address_group_value' + assert jsonified_request["sourceAddressGroup"] == "source_address_group_value" client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.clone_address_group_items(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_clone_address_group_items_rest_unset_required_fields(): - transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.clone_address_group_items._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("addressGroup", "sourceAddressGroup", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "addressGroup", + "sourceAddressGroup", + ) + ) + ) def test_clone_address_group_items_rest_flattened(): @@ -5324,17 +6221,19 @@ def test_clone_address_group_items_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) mock_args.update(sample_request) @@ -5342,7 +6241,7 @@ def test_clone_address_group_items_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -5352,10 +6251,14 @@ def test_clone_address_group_items_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:cloneItems" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:cloneItems" + % client.transport._host, + args[1], + ) -def test_clone_address_group_items_rest_flattened_error(transport: str = 'rest'): +def test_clone_address_group_items_rest_flattened_error(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5366,8 +6269,8 @@ def test_clone_address_group_items_rest_flattened_error(transport: str = 'rest') with pytest.raises(ValueError): client.clone_address_group_items( gcn_address_group.CloneAddressGroupItemsRequest(), - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) @@ -5385,12 +6288,18 @@ def test_delete_address_group_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_address_group in client._transport._wrapped_methods + assert ( + client._transport.delete_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_address_group + ] = mock_rpc request = {} client.delete_address_group(request) @@ -5409,57 +6318,62 @@ def test_delete_address_group_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_address_group_rest_required_fields(request_type=address_group.DeleteAddressGroupRequest): +def test_delete_address_group_rest_required_fields( + request_type=address_group.DeleteAddressGroupRequest, +): transport_class = transports.AddressGroupServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_address_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_address_group._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", )) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -5467,24 +6381,24 @@ def test_delete_address_group_rest_required_fields(request_type=address_group.De response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_address_group(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_delete_address_group_rest_unset_required_fields(): - transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_address_group._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) def test_delete_address_group_rest_flattened(): @@ -5494,16 +6408,18 @@ def test_delete_address_group_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "name": "projects/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -5511,7 +6427,7 @@ def test_delete_address_group_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -5521,10 +6437,14 @@ def test_delete_address_group_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/addressGroups/*}" + % client.transport._host, + args[1], + ) -def test_delete_address_group_rest_flattened_error(transport: str = 'rest'): +def test_delete_address_group_rest_flattened_error(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5535,7 +6455,7 @@ def test_delete_address_group_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.delete_address_group( address_group.DeleteAddressGroupRequest(), - name='name_value', + name="name_value", ) @@ -5553,12 +6473,19 @@ def test_list_address_group_references_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_address_group_references in client._transport._wrapped_methods + assert ( + client._transport.list_address_group_references + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_address_group_references] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_address_group_references + ] = mock_rpc request = {} client.list_address_group_references(request) @@ -5573,57 +6500,67 @@ def test_list_address_group_references_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_address_group_references_rest_required_fields(request_type=gcn_address_group.ListAddressGroupReferencesRequest): +def test_list_address_group_references_rest_required_fields( + request_type=gcn_address_group.ListAddressGroupReferencesRequest, +): transport_class = transports.AddressGroupServiceRestTransport request_init = {} request_init["address_group"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_group_references._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_address_group_references._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["addressGroup"] = 'address_group_value' + jsonified_request["addressGroup"] = "address_group_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_group_references._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_address_group_references._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "addressGroup" in jsonified_request - assert jsonified_request["addressGroup"] == 'address_group_value' + assert jsonified_request["addressGroup"] == "address_group_value" client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = gcn_address_group.ListAddressGroupReferencesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -5631,27 +6568,39 @@ def test_list_address_group_references_rest_required_fields(request_type=gcn_add response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_address_group_references(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_address_group_references_rest_unset_required_fields(): - transport = transports.AddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - unset_fields = transport.list_address_group_references._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("addressGroup", ))) + unset_fields = transport.list_address_group_references._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("addressGroup",)) + ) def test_list_address_group_references_rest_flattened(): @@ -5661,16 +6610,18 @@ def test_list_address_group_references_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = gcn_address_group.ListAddressGroupReferencesResponse() # get arguments that satisfy an http rule for this method - sample_request = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - address_group='address_group_value', + address_group="address_group_value", ) mock_args.update(sample_request) @@ -5678,9 +6629,11 @@ def test_list_address_group_references_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -5690,10 +6643,14 @@ def test_list_address_group_references_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:listReferences" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{address_group=projects/*/locations/*/addressGroups/*}:listReferences" + % client.transport._host, + args[1], + ) -def test_list_address_group_references_rest_flattened_error(transport: str = 'rest'): +def test_list_address_group_references_rest_flattened_error(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5704,20 +6661,20 @@ def test_list_address_group_references_rest_flattened_error(transport: str = 're with pytest.raises(ValueError): client.list_address_group_references( gcn_address_group.ListAddressGroupReferencesRequest(), - address_group='address_group_value', + address_group="address_group_value", ) -def test_list_address_group_references_rest_pager(transport: str = 'rest'): +def test_list_address_group_references_rest_pager(transport: str = "rest"): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: + # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( gcn_address_group.ListAddressGroupReferencesResponse( @@ -5726,17 +6683,17 @@ def test_list_address_group_references_rest_pager(transport: str = 'rest'): gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='abc', + next_page_token="abc", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[], - next_page_token='def', + next_page_token="def", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='ghi', + next_page_token="ghi", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ @@ -5749,24 +6706,34 @@ def test_list_address_group_references_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(gcn_address_group.ListAddressGroupReferencesResponse.to_json(x) for x in response) + response = tuple( + gcn_address_group.ListAddressGroupReferencesResponse.to_json(x) + for x in response + ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') + return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } pager = client.list_address_group_references(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) - for i in results) + assert all( + isinstance( + i, + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference, + ) + for i in results + ) pages = list(client.list_address_group_references(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -5808,8 +6775,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = AddressGroupServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() + client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -5831,6 +6797,7 @@ def test_transport_instance(): client = AddressGroupServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AddressGroupServiceGrpcTransport( @@ -5845,18 +6812,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.AddressGroupServiceGrpcTransport, - transports.AddressGroupServiceGrpcAsyncIOTransport, - transports.AddressGroupServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AddressGroupServiceGrpcTransport, + transports.AddressGroupServiceGrpcAsyncIOTransport, + transports.AddressGroupServiceRestTransport, + ], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + 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_kind_grpc(): transport = AddressGroupServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -5866,8 +6838,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -5882,8 +6853,8 @@ def test_list_address_groups_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: call.return_value = address_group.ListAddressGroupsResponse() client.list_address_groups(request=None) @@ -5905,8 +6876,8 @@ def test_get_address_group_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: call.return_value = address_group.AddressGroup() client.get_address_group(request=None) @@ -5928,9 +6899,9 @@ def test_create_address_group_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.create_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.create_address_group(request=None) # Establish that the underlying stub method was called. @@ -5951,9 +6922,9 @@ def test_update_address_group_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.update_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.update_address_group(request=None) # Establish that the underlying stub method was called. @@ -5974,9 +6945,9 @@ def test_add_address_group_items_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.add_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.add_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -5997,9 +6968,9 @@ def test_remove_address_group_items_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.remove_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.remove_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -6020,9 +6991,9 @@ def test_clone_address_group_items_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.clone_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.clone_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -6043,9 +7014,9 @@ def test_delete_address_group_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.delete_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.delete_address_group(request=None) # Establish that the underlying stub method was called. @@ -6066,8 +7037,8 @@ def test_list_address_group_references_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() client.list_address_group_references(request=None) @@ -6088,8 +7059,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -6105,13 +7075,15 @@ async def test_list_address_groups_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.ListAddressGroupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) await client.list_address_groups(request=None) # Establish that the underlying stub method was called. @@ -6133,18 +7105,20 @@ async def test_get_address_group_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup( - name='name_value', - description='description_value', - type_=address_group.AddressGroup.Type.IPV4, - items=['items_value'], - capacity=846, - self_link='self_link_value', - purpose=[address_group.AddressGroup.Purpose.DEFAULT], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.AddressGroup( + name="name_value", + description="description_value", + type_=address_group.AddressGroup.Type.IPV4, + items=["items_value"], + capacity=846, + self_link="self_link_value", + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + ) + ) await client.get_address_group(request=None) # Establish that the underlying stub method was called. @@ -6166,11 +7140,11 @@ async def test_create_address_group_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.create_address_group(request=None) @@ -6193,11 +7167,11 @@ async def test_update_address_group_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.update_address_group(request=None) @@ -6220,11 +7194,11 @@ async def test_add_address_group_items_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.add_address_group_items(request=None) @@ -6247,11 +7221,11 @@ async def test_remove_address_group_items_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.remove_address_group_items(request=None) @@ -6274,11 +7248,11 @@ async def test_clone_address_group_items_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.clone_address_group_items(request=None) @@ -6301,11 +7275,11 @@ async def test_delete_address_group_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.delete_address_group(request=None) @@ -6328,12 +7302,14 @@ async def test_list_address_group_references_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_address_group_references(request=None) # Establish that the underlying stub method was called. @@ -6351,20 +7327,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_list_address_groups_rest_bad_request(request_type=address_group.ListAddressGroupsRequest): +def test_list_address_groups_rest_bad_request( + request_type=address_group.ListAddressGroupsRequest, +): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -6373,26 +7352,28 @@ def test_list_address_groups_rest_bad_request(request_type=address_group.ListAdd client.list_address_groups(request) -@pytest.mark.parametrize("request_type", [ - address_group.ListAddressGroupsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + address_group.ListAddressGroupsRequest, + dict, + ], +) def test_list_address_groups_rest_call_success(request_type): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = address_group.ListAddressGroupsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) # Wrap the value into a proper Response obj @@ -6402,34 +7383,45 @@ def test_list_address_groups_rest_call_success(request_type): # Convert return value to protobuf type return_value = address_group.ListAddressGroupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_address_groups(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_address_groups_rest_interceptors(null_interceptor): transport = transports.AddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AddressGroupServiceRestInterceptor(), + ) client = AddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_list_address_groups") as post, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_list_address_groups_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_list_address_groups") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "post_list_address_groups" + ) as post, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "post_list_address_groups_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "pre_list_address_groups" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = address_group.ListAddressGroupsRequest.pb(address_group.ListAddressGroupsRequest()) + pb_message = address_group.ListAddressGroupsRequest.pb( + address_group.ListAddressGroupsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6440,39 +7432,53 @@ def test_list_address_groups_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = address_group.ListAddressGroupsResponse.to_json(address_group.ListAddressGroupsResponse()) + return_value = address_group.ListAddressGroupsResponse.to_json( + address_group.ListAddressGroupsResponse() + ) req.return_value.content = return_value request = address_group.ListAddressGroupsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = address_group.ListAddressGroupsResponse() - post_with_metadata.return_value = address_group.ListAddressGroupsResponse(), metadata + post_with_metadata.return_value = ( + address_group.ListAddressGroupsResponse(), + metadata, + ) - client.list_address_groups(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_address_groups( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_address_group_rest_bad_request(request_type=address_group.GetAddressGroupRequest): +def test_get_address_group_rest_bad_request( + request_type=address_group.GetAddressGroupRequest, +): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/addressGroups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -6481,31 +7487,33 @@ def test_get_address_group_rest_bad_request(request_type=address_group.GetAddres client.get_address_group(request) -@pytest.mark.parametrize("request_type", [ - address_group.GetAddressGroupRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + address_group.GetAddressGroupRequest, + dict, + ], +) def test_get_address_group_rest_call_success(request_type): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/addressGroups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = address_group.AddressGroup( - name='name_value', - description='description_value', - type_=address_group.AddressGroup.Type.IPV4, - items=['items_value'], - capacity=846, - self_link='self_link_value', - purpose=[address_group.AddressGroup.Purpose.DEFAULT], + name="name_value", + description="description_value", + type_=address_group.AddressGroup.Type.IPV4, + items=["items_value"], + capacity=846, + self_link="self_link_value", + purpose=[address_group.AddressGroup.Purpose.DEFAULT], ) # Wrap the value into a proper Response obj @@ -6515,19 +7523,19 @@ def test_get_address_group_rest_call_success(request_type): # Convert return value to protobuf type return_value = address_group.AddressGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_address_group(request) # Establish that the response is the type that we expect. assert isinstance(response, address_group.AddressGroup) - assert response.name == 'name_value' - assert response.description == 'description_value' + assert response.name == "name_value" + assert response.description == "description_value" assert response.type_ == address_group.AddressGroup.Type.IPV4 - assert response.items == ['items_value'] + assert response.items == ["items_value"] assert response.capacity == 846 - assert response.self_link == 'self_link_value' + assert response.self_link == "self_link_value" assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] @@ -6535,19 +7543,30 @@ def test_get_address_group_rest_call_success(request_type): def test_get_address_group_rest_interceptors(null_interceptor): transport = transports.AddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AddressGroupServiceRestInterceptor(), + ) client = AddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_get_address_group") as post, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_get_address_group_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_get_address_group") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "post_get_address_group" + ) as post, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "post_get_address_group_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "pre_get_address_group" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = address_group.GetAddressGroupRequest.pb(address_group.GetAddressGroupRequest()) + pb_message = address_group.GetAddressGroupRequest.pb( + address_group.GetAddressGroupRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6562,7 +7581,7 @@ def test_get_address_group_rest_interceptors(null_interceptor): req.return_value.content = return_value request = address_group.GetAddressGroupRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -6570,27 +7589,36 @@ def test_get_address_group_rest_interceptors(null_interceptor): post.return_value = address_group.AddressGroup() post_with_metadata.return_value = address_group.AddressGroup(), metadata - client.get_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_address_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_create_address_group_rest_bad_request(request_type=gcn_address_group.CreateAddressGroupRequest): +def test_create_address_group_rest_bad_request( + request_type=gcn_address_group.CreateAddressGroupRequest, +): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -6599,25 +7627,40 @@ def test_create_address_group_rest_bad_request(request_type=gcn_address_group.Cr client.create_address_group(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.CreateAddressGroupRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.CreateAddressGroupRequest, + dict, + ], +) def test_create_address_group_rest_call_success(request_type): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["address_group"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'items': ['items_value1', 'items_value2'], 'capacity': 846, 'self_link': 'self_link_value', 'purpose': [1]} + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["address_group"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "items": ["items_value1", "items_value2"], + "capacity": 846, + "self_link": "self_link_value", + "purpose": [1], + } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = gcn_address_group.CreateAddressGroupRequest.meta.fields["address_group"] + test_field = gcn_address_group.CreateAddressGroupRequest.meta.fields[ + "address_group" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -6631,7 +7674,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -6645,7 +7688,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["address_group"].items(): # pragma: NO COVER + for field, value in request_init["address_group"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -6660,12 +7703,16 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -6678,15 +7725,15 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_address_group(request) @@ -6699,20 +7746,32 @@ def get_message_fields(field): def test_create_address_group_rest_interceptors(null_interceptor): transport = transports.AddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AddressGroupServiceRestInterceptor(), + ) client = AddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_create_address_group") as post, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_create_address_group_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_create_address_group") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "post_create_address_group" + ) as post, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "post_create_address_group_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "pre_create_address_group" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.CreateAddressGroupRequest.pb(gcn_address_group.CreateAddressGroupRequest()) + pb_message = gcn_address_group.CreateAddressGroupRequest.pb( + gcn_address_group.CreateAddressGroupRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6727,7 +7786,7 @@ def test_create_address_group_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gcn_address_group.CreateAddressGroupRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -6735,27 +7794,40 @@ def test_create_address_group_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.create_address_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_address_group_rest_bad_request(request_type=gcn_address_group.UpdateAddressGroupRequest): +def test_update_address_group_rest_bad_request( + request_type=gcn_address_group.UpdateAddressGroupRequest, +): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'}} + request_init = { + "address_group": { + "name": "projects/sample1/locations/sample2/addressGroups/sample3" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -6764,25 +7836,44 @@ def test_update_address_group_rest_bad_request(request_type=gcn_address_group.Up client.update_address_group(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.UpdateAddressGroupRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.UpdateAddressGroupRequest, + dict, + ], +) def test_update_address_group_rest_call_success(request_type): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'}} - request_init["address_group"] = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'items': ['items_value1', 'items_value2'], 'capacity': 846, 'self_link': 'self_link_value', 'purpose': [1]} + request_init = { + "address_group": { + "name": "projects/sample1/locations/sample2/addressGroups/sample3" + } + } + request_init["address_group"] = { + "name": "projects/sample1/locations/sample2/addressGroups/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "items": ["items_value1", "items_value2"], + "capacity": 846, + "self_link": "self_link_value", + "purpose": [1], + } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = gcn_address_group.UpdateAddressGroupRequest.meta.fields["address_group"] + test_field = gcn_address_group.UpdateAddressGroupRequest.meta.fields[ + "address_group" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -6796,7 +7887,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -6810,7 +7901,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["address_group"].items(): # pragma: NO COVER + for field, value in request_init["address_group"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -6825,12 +7916,16 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -6843,15 +7938,15 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_address_group(request) @@ -6864,20 +7959,32 @@ def get_message_fields(field): def test_update_address_group_rest_interceptors(null_interceptor): transport = transports.AddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AddressGroupServiceRestInterceptor(), + ) client = AddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_update_address_group") as post, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_update_address_group_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_update_address_group") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "post_update_address_group" + ) as post, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "post_update_address_group_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "pre_update_address_group" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.UpdateAddressGroupRequest.pb(gcn_address_group.UpdateAddressGroupRequest()) + pb_message = gcn_address_group.UpdateAddressGroupRequest.pb( + gcn_address_group.UpdateAddressGroupRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6892,7 +7999,7 @@ def test_update_address_group_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gcn_address_group.UpdateAddressGroupRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -6900,27 +8007,38 @@ def test_update_address_group_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_address_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_add_address_group_items_rest_bad_request(request_type=gcn_address_group.AddAddressGroupItemsRequest): +def test_add_address_group_items_rest_bad_request( + request_type=gcn_address_group.AddAddressGroupItemsRequest, +): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -6929,30 +8047,34 @@ def test_add_address_group_items_rest_bad_request(request_type=gcn_address_group client.add_address_group_items(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.AddAddressGroupItemsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.AddAddressGroupItemsRequest, + dict, + ], +) def test_add_address_group_items_rest_call_success(request_type): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.add_address_group_items(request) @@ -6965,20 +8087,32 @@ def test_add_address_group_items_rest_call_success(request_type): def test_add_address_group_items_rest_interceptors(null_interceptor): transport = transports.AddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AddressGroupServiceRestInterceptor(), + ) client = AddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_add_address_group_items") as post, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_add_address_group_items_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_add_address_group_items") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "post_add_address_group_items" + ) as post, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "post_add_address_group_items_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "pre_add_address_group_items" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.AddAddressGroupItemsRequest.pb(gcn_address_group.AddAddressGroupItemsRequest()) + pb_message = gcn_address_group.AddAddressGroupItemsRequest.pb( + gcn_address_group.AddAddressGroupItemsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6993,7 +8127,7 @@ def test_add_address_group_items_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gcn_address_group.AddAddressGroupItemsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -7001,27 +8135,38 @@ def test_add_address_group_items_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.add_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.add_address_group_items( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_remove_address_group_items_rest_bad_request(request_type=gcn_address_group.RemoveAddressGroupItemsRequest): +def test_remove_address_group_items_rest_bad_request( + request_type=gcn_address_group.RemoveAddressGroupItemsRequest, +): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -7030,30 +8175,34 @@ def test_remove_address_group_items_rest_bad_request(request_type=gcn_address_gr client.remove_address_group_items(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.RemoveAddressGroupItemsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.RemoveAddressGroupItemsRequest, + dict, + ], +) def test_remove_address_group_items_rest_call_success(request_type): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.remove_address_group_items(request) @@ -7066,20 +8215,32 @@ def test_remove_address_group_items_rest_call_success(request_type): def test_remove_address_group_items_rest_interceptors(null_interceptor): transport = transports.AddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AddressGroupServiceRestInterceptor(), + ) client = AddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_remove_address_group_items") as post, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_remove_address_group_items_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_remove_address_group_items") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "post_remove_address_group_items" + ) as post, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "post_remove_address_group_items_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "pre_remove_address_group_items" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.RemoveAddressGroupItemsRequest.pb(gcn_address_group.RemoveAddressGroupItemsRequest()) + pb_message = gcn_address_group.RemoveAddressGroupItemsRequest.pb( + gcn_address_group.RemoveAddressGroupItemsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7094,7 +8255,7 @@ def test_remove_address_group_items_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gcn_address_group.RemoveAddressGroupItemsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -7102,27 +8263,38 @@ def test_remove_address_group_items_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.remove_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.remove_address_group_items( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_clone_address_group_items_rest_bad_request(request_type=gcn_address_group.CloneAddressGroupItemsRequest): +def test_clone_address_group_items_rest_bad_request( + request_type=gcn_address_group.CloneAddressGroupItemsRequest, +): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -7131,30 +8303,34 @@ def test_clone_address_group_items_rest_bad_request(request_type=gcn_address_gro client.clone_address_group_items(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.CloneAddressGroupItemsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.CloneAddressGroupItemsRequest, + dict, + ], +) def test_clone_address_group_items_rest_call_success(request_type): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.clone_address_group_items(request) @@ -7167,20 +8343,32 @@ def test_clone_address_group_items_rest_call_success(request_type): def test_clone_address_group_items_rest_interceptors(null_interceptor): transport = transports.AddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AddressGroupServiceRestInterceptor(), + ) client = AddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_clone_address_group_items") as post, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_clone_address_group_items_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_clone_address_group_items") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "post_clone_address_group_items" + ) as post, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "post_clone_address_group_items_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "pre_clone_address_group_items" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.CloneAddressGroupItemsRequest.pb(gcn_address_group.CloneAddressGroupItemsRequest()) + pb_message = gcn_address_group.CloneAddressGroupItemsRequest.pb( + gcn_address_group.CloneAddressGroupItemsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7195,7 +8383,7 @@ def test_clone_address_group_items_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gcn_address_group.CloneAddressGroupItemsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -7203,27 +8391,36 @@ def test_clone_address_group_items_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.clone_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.clone_address_group_items( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_address_group_rest_bad_request(request_type=address_group.DeleteAddressGroupRequest): +def test_delete_address_group_rest_bad_request( + request_type=address_group.DeleteAddressGroupRequest, +): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/addressGroups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -7232,30 +8429,32 @@ def test_delete_address_group_rest_bad_request(request_type=address_group.Delete client.delete_address_group(request) -@pytest.mark.parametrize("request_type", [ - address_group.DeleteAddressGroupRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + address_group.DeleteAddressGroupRequest, + dict, + ], +) def test_delete_address_group_rest_call_success(request_type): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/addressGroups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_address_group(request) @@ -7268,20 +8467,32 @@ def test_delete_address_group_rest_call_success(request_type): def test_delete_address_group_rest_interceptors(null_interceptor): transport = transports.AddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AddressGroupServiceRestInterceptor(), + ) client = AddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_delete_address_group") as post, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_delete_address_group_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_delete_address_group") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "post_delete_address_group" + ) as post, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "post_delete_address_group_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, "pre_delete_address_group" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = address_group.DeleteAddressGroupRequest.pb(address_group.DeleteAddressGroupRequest()) + pb_message = address_group.DeleteAddressGroupRequest.pb( + address_group.DeleteAddressGroupRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7296,7 +8507,7 @@ def test_delete_address_group_rest_interceptors(null_interceptor): req.return_value.content = return_value request = address_group.DeleteAddressGroupRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -7304,27 +8515,38 @@ def test_delete_address_group_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_address_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_address_group_references_rest_bad_request(request_type=gcn_address_group.ListAddressGroupReferencesRequest): +def test_list_address_group_references_rest_bad_request( + request_type=gcn_address_group.ListAddressGroupReferencesRequest, +): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -7333,25 +8555,29 @@ def test_list_address_group_references_rest_bad_request(request_type=gcn_address client.list_address_group_references(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.ListAddressGroupReferencesRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.ListAddressGroupReferencesRequest, + dict, + ], +) def test_list_address_group_references_rest_call_success(request_type): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'projects/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "projects/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = gcn_address_group.ListAddressGroupReferencesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -7359,35 +8585,50 @@ def test_list_address_group_references_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_address_group_references(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupReferencesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_address_group_references_rest_interceptors(null_interceptor): transport = transports.AddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AddressGroupServiceRestInterceptor(), + ) client = AddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_list_address_group_references") as post, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "post_list_address_group_references_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AddressGroupServiceRestInterceptor, "pre_list_address_group_references") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "post_list_address_group_references", + ) as post, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "post_list_address_group_references_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AddressGroupServiceRestInterceptor, + "pre_list_address_group_references", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.ListAddressGroupReferencesRequest.pb(gcn_address_group.ListAddressGroupReferencesRequest()) + pb_message = gcn_address_group.ListAddressGroupReferencesRequest.pb( + gcn_address_group.ListAddressGroupReferencesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7398,19 +8639,30 @@ def test_list_address_group_references_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gcn_address_group.ListAddressGroupReferencesResponse.to_json(gcn_address_group.ListAddressGroupReferencesResponse()) + return_value = gcn_address_group.ListAddressGroupReferencesResponse.to_json( + gcn_address_group.ListAddressGroupReferencesResponse() + ) req.return_value.content = return_value request = gcn_address_group.ListAddressGroupReferencesRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = gcn_address_group.ListAddressGroupReferencesResponse() - post_with_metadata.return_value = gcn_address_group.ListAddressGroupReferencesResponse(), metadata + post_with_metadata.return_value = ( + gcn_address_group.ListAddressGroupReferencesResponse(), + metadata, + ) - client.list_address_group_references(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_address_group_references( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -7423,13 +8675,17 @@ def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationReq transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7438,20 +8694,23 @@ def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationReq client.get_location(request) -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) def test_get_location_rest(request_type): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2'} + request_init = {"name": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = locations_pb2.Location() @@ -7459,7 +8718,7 @@ def test_get_location_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7470,19 +8729,23 @@ def test_get_location_rest(request_type): assert isinstance(response, locations_pb2.Location) -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) + request = json_format.ParseDict({"name": "projects/sample1"}, request) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7491,20 +8754,23 @@ def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocation client.list_locations(request) -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) def test_list_locations_rest(request_type): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1'} + request_init = {"name": "projects/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = locations_pb2.ListLocationsResponse() @@ -7512,7 +8778,7 @@ def test_list_locations_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7523,19 +8789,28 @@ def test_list_locations_rest(request_type): assert isinstance(response, locations_pb2.ListLocationsResponse) -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + request = json_format.ParseDict( + { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + }, + request, + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7544,20 +8819,25 @@ def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolic client.get_iam_policy(request) -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) def test_get_iam_policy_rest(request_type): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request_init = { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = policy_pb2.Policy() @@ -7565,7 +8845,7 @@ def test_get_iam_policy_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7576,19 +8856,28 @@ def test_get_iam_policy_rest(request_type): assert isinstance(response, policy_pb2.Policy) -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + request = json_format.ParseDict( + { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + }, + request, + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7597,20 +8886,25 @@ def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolic client.set_iam_policy(request) -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) def test_set_iam_policy_rest(request_type): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request_init = { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = policy_pb2.Policy() @@ -7618,7 +8912,7 @@ def test_set_iam_policy_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7629,19 +8923,28 @@ def test_set_iam_policy_rest(request_type): assert isinstance(response, policy_pb2.Policy) -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + request = json_format.ParseDict( + { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + }, + request, + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7650,20 +8953,25 @@ def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestI client.test_iam_permissions(request) -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) def test_test_iam_permissions_rest(request_type): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request_init = { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = iam_policy_pb2.TestIamPermissionsResponse() @@ -7671,7 +8979,7 @@ def test_test_iam_permissions_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7682,19 +8990,25 @@ def test_test_iam_permissions_rest(request_type): assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7703,28 +9017,31 @@ def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOpe client.cancel_operation(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) def test_cancel_operation_rest(request_type): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7735,19 +9052,25 @@ def test_cancel_operation_rest(request_type): assert response is None -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7756,28 +9079,31 @@ def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOpe client.delete_operation(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) def test_delete_operation_rest(request_type): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7788,19 +9114,25 @@ def test_delete_operation_rest(request_type): assert response is None -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7809,20 +9141,23 @@ def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperation client.get_operation(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) def test_get_operation_rest(request_type): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = operations_pb2.Operation() @@ -7830,7 +9165,7 @@ def test_get_operation_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7841,19 +9176,25 @@ def test_get_operation_rest(request_type): assert isinstance(response, operations_pb2.Operation) -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7862,20 +9203,23 @@ def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperat client.list_operations(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) def test_list_operations_rest(request_type): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2'} + request_init = {"name": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = operations_pb2.ListOperationsResponse() @@ -7883,7 +9227,7 @@ def test_list_operations_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7893,10 +9237,10 @@ def test_list_operations_rest(request_type): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + def test_initialize_client_w_rest(): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -7911,8 +9255,8 @@ def test_list_address_groups_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: client.list_address_groups(request=None) # Establish that the underlying stub method was called. @@ -7933,8 +9277,8 @@ def test_get_address_group_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: client.get_address_group(request=None) # Establish that the underlying stub method was called. @@ -7955,8 +9299,8 @@ def test_create_address_group_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: client.create_address_group(request=None) # Establish that the underlying stub method was called. @@ -7977,8 +9321,8 @@ def test_update_address_group_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: client.update_address_group(request=None) # Establish that the underlying stub method was called. @@ -7999,8 +9343,8 @@ def test_add_address_group_items_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: client.add_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -8021,8 +9365,8 @@ def test_remove_address_group_items_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: client.remove_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -8043,8 +9387,8 @@ def test_clone_address_group_items_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: client.clone_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -8065,8 +9409,8 @@ def test_delete_address_group_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: client.delete_address_group(request=None) # Establish that the underlying stub method was called. @@ -8087,8 +9431,8 @@ def test_list_address_group_references_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: client.list_address_group_references(request=None) # Establish that the underlying stub method was called. @@ -8109,12 +9453,13 @@ def test_address_group_service_rest_lro_client(): # Ensure that we have an api-core operations client. assert isinstance( transport.operations_client, -operations_v1.AbstractOperationsClient, + operations_v1.AbstractOperationsClient, ) # Ensure that subsequent calls to the property send the exact same object. assert transport.operations_client is transport.operations_client + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = AddressGroupServiceClient( @@ -8125,18 +9470,21 @@ def test_transport_grpc_default(): transports.AddressGroupServiceGrpcTransport, ) + def test_address_group_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AddressGroupServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_address_group_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.cloud.network_security_v1.services.address_group_service.transports.AddressGroupServiceTransport.__init__') as Transport: + with mock.patch( + "google.cloud.network_security_v1.services.address_group_service.transports.AddressGroupServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.AddressGroupServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -8145,24 +9493,24 @@ def test_address_group_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'list_address_groups', - 'get_address_group', - 'create_address_group', - 'update_address_group', - 'add_address_group_items', - 'remove_address_group_items', - 'clone_address_group_items', - 'delete_address_group', - 'list_address_group_references', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', + "list_address_groups", + "get_address_group", + "create_address_group", + "update_address_group", + "add_address_group_items", + "remove_address_group_items", + "clone_address_group_items", + "delete_address_group", + "list_address_group_references", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", ) for method in methods: with pytest.raises(NotImplementedError): @@ -8178,7 +9526,7 @@ def test_address_group_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -8187,25 +9535,30 @@ def test_address_group_service_base_transport(): def test_address_group_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.network_security_v1.services.address_group_service.transports.AddressGroupServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.network_security_v1.services.address_group_service.transports.AddressGroupServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AddressGroupServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + load_creds.assert_called_once_with( + "credentials.json", scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) def test_address_group_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.network_security_v1.services.address_group_service.transports.AddressGroupServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.network_security_v1.services.address_group_service.transports.AddressGroupServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AddressGroupServiceTransport() @@ -8214,14 +9567,12 @@ def test_address_group_service_base_transport_with_adc(): def test_address_group_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) AddressGroupServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id=None, ) @@ -8236,12 +9587,12 @@ def test_address_group_service_auth_adc(): def test_address_group_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: + 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',), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) @@ -8255,48 +9606,45 @@ def test_address_group_service_transport_auth_adc(transport_class): ], ) def test_address_group_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) adc.return_value = (gdch_mock, None) transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) + gdch_mock.with_gdch_audience.assert_called_once_with(e) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.AddressGroupServiceGrpcTransport, grpc_helpers), - (transports.AddressGroupServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.AddressGroupServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_address_group_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( + 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"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "networksecurity.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=["1", "2"], default_host="networksecurity.googleapis.com", ssl_credentials=None, @@ -8307,9 +9655,15 @@ def test_address_group_service_transport_create_channel(transport_class, grpc_he ) -@pytest.mark.parametrize("transport_class", [transports.AddressGroupServiceGrpcTransport, transports.AddressGroupServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AddressGroupServiceGrpcTransport, + transports.AddressGroupServiceGrpcAsyncIOTransport, + ], +) def test_address_group_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -8319,7 +9673,7 @@ def test_address_group_service_grpc_transport_client_cert_source_for_mtls( transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -8340,61 +9694,77 @@ def test_address_group_service_grpc_transport_client_cert_source_for_mtls( with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + 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 + certificate_chain=expected_cert, private_key=expected_key ) + def test_address_group_service_http_transport_client_cert_source_for_mtls(): cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.AddressGroupServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.AddressGroupServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_address_group_service_host_no_port(transport_name): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com'), - transport=transport_name, + client_options=client_options.ClientOptions( + api_endpoint="networksecurity.googleapis.com" + ), + transport=transport_name, ) assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networksecurity.googleapis.com' + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" ) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_address_group_service_host_with_port(transport_name): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="networksecurity.googleapis.com:8000" + ), transport=transport_name, ) assert client.transport._host == ( - 'networksecurity.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networksecurity.googleapis.com:8000' + "networksecurity.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com:8000" ) -@pytest.mark.parametrize("transport_name", [ - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) def test_address_group_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -8433,8 +9803,10 @@ def test_address_group_service_client_transport_session_collision(transport_name session1 = client1.transport.list_address_group_references._session session2 = client2.transport.list_address_group_references._session assert session1 != session2 + + def test_address_group_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.AddressGroupServiceGrpcTransport( @@ -8447,7 +9819,7 @@ def test_address_group_service_grpc_transport_channel(): def test_address_group_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.AddressGroupServiceGrpcAsyncIOTransport( @@ -8461,12 +9833,22 @@ def test_address_group_service_grpc_asyncio_transport_channel(): # 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.AddressGroupServiceGrpcTransport, transports.AddressGroupServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AddressGroupServiceGrpcTransport, + transports.AddressGroupServiceGrpcAsyncIOTransport, + ], +) def test_address_group_service_transport_channel_mtls_with_client_cert_source( - transport_class + 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: + 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 @@ -8475,7 +9857,7 @@ def test_address_group_service_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -8505,17 +9887,23 @@ def test_address_group_service_transport_channel_mtls_with_client_cert_source( # 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.AddressGroupServiceGrpcTransport, transports.AddressGroupServiceGrpcAsyncIOTransport]) -def test_address_group_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AddressGroupServiceGrpcTransport, + transports.AddressGroupServiceGrpcAsyncIOTransport, + ], +) +def test_address_group_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: + 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() @@ -8546,7 +9934,7 @@ def test_address_group_service_transport_channel_mtls_with_adc( def test_address_group_service_grpc_lro_client(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -8563,7 +9951,7 @@ def test_address_group_service_grpc_lro_client(): def test_address_group_service_grpc_lro_async_client(): client = AddressGroupServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', + transport="grpc_asyncio", ) transport = client.transport @@ -8581,8 +9969,16 @@ def test_address_group_path(): project = "squid" location = "clam" address_group = "whelk" - expected = "projects/{project}/locations/{location}/addressGroups/{address_group}".format(project=project, location=location, address_group=address_group, ) - actual = AddressGroupServiceClient.address_group_path(project, location, address_group) + expected = ( + "projects/{project}/locations/{location}/addressGroups/{address_group}".format( + project=project, + location=location, + address_group=address_group, + ) + ) + actual = AddressGroupServiceClient.address_group_path( + project, location, address_group + ) assert expected == actual @@ -8598,9 +9994,12 @@ def test_parse_address_group_path(): actual = AddressGroupServiceClient.parse_address_group_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = AddressGroupServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -8615,9 +10014,12 @@ def test_parse_common_billing_account_path(): actual = AddressGroupServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = AddressGroupServiceClient.common_folder_path(folder) assert expected == actual @@ -8632,9 +10034,12 @@ def test_parse_common_folder_path(): actual = AddressGroupServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = AddressGroupServiceClient.common_organization_path(organization) assert expected == actual @@ -8649,9 +10054,12 @@ def test_parse_common_organization_path(): actual = AddressGroupServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = AddressGroupServiceClient.common_project_path(project) assert expected == actual @@ -8666,10 +10074,14 @@ def test_parse_common_project_path(): actual = AddressGroupServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = AddressGroupServiceClient.common_location_path(project, location) assert expected == actual @@ -8689,14 +10101,18 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.AddressGroupServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AddressGroupServiceTransport, "_prep_wrapped_messages" + ) as prep: client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.AddressGroupServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AddressGroupServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = AddressGroupServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -8707,7 +10123,8 @@ def test_client_with_default_client_info(): def test_delete_operation(transport: str = "grpc"): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -8726,10 +10143,13 @@ def test_delete_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert response is None + + @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -8739,9 +10159,7 @@ async def test_delete_operation_async(transport: str = "grpc_asyncio"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_operation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8751,6 +10169,7 @@ async def test_delete_operation_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert response is None + def test_delete_operation_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8763,7 +10182,7 @@ def test_delete_operation_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None + call.return_value = None client.delete_operation(request) # Establish that the underlying gRPC stub method was called. @@ -8773,7 +10192,12 @@ def test_delete_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = AddressGroupServiceAsyncClient( @@ -8787,9 +10211,7 @@ async def test_delete_operation_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_operation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8798,7 +10220,11 @@ async def test_delete_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_delete_operation_from_dict(): client = AddressGroupServiceClient( @@ -8815,6 +10241,8 @@ def test_delete_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = AddressGroupServiceAsyncClient( @@ -8823,9 +10251,7 @@ async def test_delete_operation_from_dict_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_operation( request={ "name": "locations", @@ -8836,7 +10262,8 @@ async def test_delete_operation_from_dict_async(): def test_cancel_operation(transport: str = "grpc"): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -8855,10 +10282,13 @@ def test_cancel_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert response is None + + @pytest.mark.asyncio async def test_cancel_operation_async(transport: str = "grpc_asyncio"): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -8868,9 +10298,7 @@ async def test_cancel_operation_async(transport: str = "grpc_asyncio"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.cancel_operation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8880,6 +10308,7 @@ async def test_cancel_operation_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert response is None + def test_cancel_operation_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8892,7 +10321,7 @@ def test_cancel_operation_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None + call.return_value = None client.cancel_operation(request) # Establish that the underlying gRPC stub method was called. @@ -8902,7 +10331,12 @@ def test_cancel_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_cancel_operation_field_headers_async(): client = AddressGroupServiceAsyncClient( @@ -8916,9 +10350,7 @@ async def test_cancel_operation_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.cancel_operation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8927,7 +10359,11 @@ async def test_cancel_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_cancel_operation_from_dict(): client = AddressGroupServiceClient( @@ -8944,6 +10380,8 @@ def test_cancel_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_cancel_operation_from_dict_async(): client = AddressGroupServiceAsyncClient( @@ -8952,9 +10390,7 @@ async def test_cancel_operation_from_dict_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.cancel_operation( request={ "name": "locations", @@ -8965,7 +10401,8 @@ async def test_cancel_operation_from_dict_async(): def test_get_operation(transport: str = "grpc"): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -8984,10 +10421,13 @@ def test_get_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) + + @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9009,6 +10449,7 @@ async def test_get_operation_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) + def test_get_operation_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9031,7 +10472,12 @@ def test_get_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = AddressGroupServiceAsyncClient( @@ -9056,7 +10502,11 @@ async def test_get_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_get_operation_from_dict(): client = AddressGroupServiceClient( @@ -9073,6 +10523,8 @@ def test_get_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = AddressGroupServiceAsyncClient( @@ -9094,7 +10546,8 @@ async def test_get_operation_from_dict_async(): def test_list_operations(transport: str = "grpc"): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9113,10 +10566,13 @@ def test_list_operations(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + + @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9138,6 +10594,7 @@ async def test_list_operations_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + def test_list_operations_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9160,7 +10617,12 @@ def test_list_operations_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = AddressGroupServiceAsyncClient( @@ -9185,7 +10647,11 @@ async def test_list_operations_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_list_operations_from_dict(): client = AddressGroupServiceClient( @@ -9202,6 +10668,8 @@ def test_list_operations_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = AddressGroupServiceAsyncClient( @@ -9223,7 +10691,8 @@ async def test_list_operations_from_dict_async(): def test_list_locations(transport: str = "grpc"): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9242,10 +10711,13 @@ def test_list_locations(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.ListLocationsResponse) + + @pytest.mark.asyncio async def test_list_locations_async(transport: str = "grpc_asyncio"): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9267,6 +10739,7 @@ async def test_list_locations_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.ListLocationsResponse) + def test_list_locations_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9289,7 +10762,12 @@ def test_list_locations_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = AddressGroupServiceAsyncClient( @@ -9314,7 +10792,11 @@ async def test_list_locations_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_list_locations_from_dict(): client = AddressGroupServiceClient( @@ -9331,6 +10813,8 @@ def test_list_locations_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = AddressGroupServiceAsyncClient( @@ -9352,7 +10836,8 @@ async def test_list_locations_from_dict_async(): def test_get_location(transport: str = "grpc"): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9371,10 +10856,13 @@ def test_get_location(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.Location) + + @pytest.mark.asyncio async def test_get_location_async(transport: str = "grpc_asyncio"): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9396,9 +10884,11 @@ async def test_get_location_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.Location) + def test_get_location_field_headers(): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials()) + credentials=ga_credentials.AnonymousCredentials() + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -9417,12 +10907,15 @@ def test_get_location_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_get_location_field_headers_async(): - client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials() - ) + client = AddressGroupServiceAsyncClient(credentials=async_anonymous_credentials()) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -9442,7 +10935,11 @@ async def test_get_location_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + def test_get_location_from_dict(): client = AddressGroupServiceClient( @@ -9459,6 +10956,8 @@ def test_get_location_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_get_location_from_dict_async(): client = AddressGroupServiceAsyncClient( @@ -9480,7 +10979,8 @@ async def test_get_location_from_dict_async(): def test_set_iam_policy(transport: str = "grpc"): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9490,7 +10990,10 @@ def test_set_iam_policy(transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) response = client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9504,10 +11007,13 @@ def test_set_iam_policy(transport: str = "grpc"): assert response.version == 774 assert response.etag == b"etag_blob" + + @pytest.mark.asyncio async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9519,7 +11025,10 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): # Designate an appropriate return value for the call. # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) ) response = await client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -9535,6 +11044,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" + def test_set_iam_policy_field_headers(): client = AddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9558,7 +11068,12 @@ def test_set_iam_policy_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = AddressGroupServiceAsyncClient( @@ -9583,7 +11098,11 @@ async def test_set_iam_policy_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + def test_set_iam_policy_from_dict(): client = AddressGroupServiceClient( @@ -9611,9 +11130,7 @@ async def test_set_iam_policy_from_dict_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.set_iam_policy( request={ @@ -9623,9 +11140,11 @@ async def test_set_iam_policy_from_dict_async(): ) call.assert_called() + def test_get_iam_policy(transport: str = "grpc"): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9635,7 +11154,10 @@ def test_get_iam_policy(transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) response = client.get_iam_policy(request) @@ -9656,7 +11178,8 @@ def test_get_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9664,12 +11187,13 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): request = iam_policy_pb2.GetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) ) response = await client.get_iam_policy(request) @@ -9711,7 +11235,10 @@ def test_get_iam_policy_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -9726,9 +11253,7 @@ async def test_get_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.get_iam_policy(request) @@ -9740,7 +11265,10 @@ async def test_get_iam_policy_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] def test_get_iam_policy_from_dict(): @@ -9760,6 +11288,7 @@ def test_get_iam_policy_from_dict(): ) call.assert_called() + @pytest.mark.asyncio async def test_get_iam_policy_from_dict_async(): client = AddressGroupServiceAsyncClient( @@ -9768,9 +11297,7 @@ async def test_get_iam_policy_from_dict_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.get_iam_policy( request={ @@ -9780,9 +11307,11 @@ async def test_get_iam_policy_from_dict_async(): ) call.assert_called() + def test_test_iam_permissions(transport: str = "grpc"): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9815,7 +11344,8 @@ def test_test_iam_permissions(transport: str = "grpc"): @pytest.mark.asyncio async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9828,7 +11358,9 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) response = await client.test_iam_permissions(request) @@ -9870,7 +11402,10 @@ def test_test_iam_permissions_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -9901,7 +11436,10 @@ async def test_test_iam_permissions_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] def test_test_iam_permissions_from_dict(): @@ -9923,6 +11461,7 @@ def test_test_iam_permissions_from_dict(): ) call.assert_called() + @pytest.mark.asyncio async def test_test_iam_permissions_from_dict_async(): client = AddressGroupServiceAsyncClient( @@ -9948,10 +11487,11 @@ async def test_test_iam_permissions_from_dict_async(): def test_transport_close_grpc(): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() @@ -9960,10 +11500,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = AddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: async with client: close.assert_not_called() close.assert_called_once() @@ -9971,10 +11512,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() @@ -9982,13 +11524,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = AddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -9997,10 +11538,17 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport), - (AddressGroupServiceAsyncClient, transports.AddressGroupServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (AddressGroupServiceClient, transports.AddressGroupServiceGrpcTransport), + ( + AddressGroupServiceAsyncClient, + transports.AddressGroupServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -10015,7 +11563,9 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, diff --git a/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py similarity index 72% rename from owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py rename to packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py index 7e2d259d528d..81577b8f77be 100644 --- a/owl-bot-staging/google-cloud-network-security/v1/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py +++ b/packages/google-cloud-network-security/tests/unit/gapic/network_security_v1/test_organization_address_group_service.py @@ -14,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,59 +22,62 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format +from collections.abc import AsyncIterable, Iterable import json import math -import pytest + from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule +from google.protobuf import json_format +import grpc +from grpc.experimental import aio from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response from requests.sessions import Session -from google.protobuf import json_format try: from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER +except ImportError: # pragma: NO COVER HAS_GOOGLE_AUTH_AIO = False +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) from google.api_core import client_options from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template from google.api_core import retry as retries +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.location import locations_pb2 -from google.cloud.network_security_v1.services.organization_address_group_service import OrganizationAddressGroupServiceAsyncClient -from google.cloud.network_security_v1.services.organization_address_group_service import OrganizationAddressGroupServiceClient -from google.cloud.network_security_v1.services.organization_address_group_service import pagers -from google.cloud.network_security_v1.services.organization_address_group_service import transports -from google.cloud.network_security_v1.types import address_group -from google.cloud.network_security_v1.types import address_group as gcn_address_group -from google.cloud.network_security_v1.types import common from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import options_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - +from google.cloud.network_security_v1.services.organization_address_group_service import ( + OrganizationAddressGroupServiceAsyncClient, + OrganizationAddressGroupServiceClient, + pagers, + transports, +) +from google.cloud.network_security_v1.types import address_group as gcn_address_group +from google.cloud.network_security_v1.types import address_group +from google.cloud.network_security_v1.types import common CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -88,9 +92,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -98,17 +104,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # 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 + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -118,102 +134,265 @@ def test__get_default_mtls_endpoint(): sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" - assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(None) is None - assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(None) is None + ) + assert ( + OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + OrganizationAddressGroupServiceClient._get_default_mtls_endpoint( + api_mtls_endpoint + ) + == api_mtls_endpoint + ) + assert ( + OrganizationAddressGroupServiceClient._get_default_mtls_endpoint( + sandbox_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + OrganizationAddressGroupServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + OrganizationAddressGroupServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + assert OrganizationAddressGroupServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert OrganizationAddressGroupServiceClient._read_environment_variables() == (True, "auto", None) + assert OrganizationAddressGroupServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + assert OrganizationAddressGroupServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError) as excinfo: OrganizationAddressGroupServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "never", None) + assert OrganizationAddressGroupServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "always", None) + assert OrganizationAddressGroupServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "auto", None) + assert OrganizationAddressGroupServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: OrganizationAddressGroupServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert OrganizationAddressGroupServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert OrganizationAddressGroupServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + def test__get_client_cert_source(): mock_provided_cert_source = mock.Mock() mock_default_cert_source = mock.Mock() - assert OrganizationAddressGroupServiceClient._get_client_cert_source(None, False) is None - assert OrganizationAddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert OrganizationAddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + OrganizationAddressGroupServiceClient._get_client_cert_source(None, False) + is None + ) + assert ( + OrganizationAddressGroupServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + OrganizationAddressGroupServiceClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + OrganizationAddressGroupServiceClient._get_client_cert_source( + None, True + ) + is mock_default_cert_source + ) + assert ( + OrganizationAddressGroupServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert OrganizationAddressGroupServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert OrganizationAddressGroupServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(OrganizationAddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceClient)) -@mock.patch.object(OrganizationAddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient)) +@mock.patch.object( + OrganizationAddressGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationAddressGroupServiceClient), +) +@mock.patch.object( + OrganizationAddressGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE - default_endpoint = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ( + OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) - assert OrganizationAddressGroupServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT - assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "always") == OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT - assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT - assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert OrganizationAddressGroupServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + OrganizationAddressGroupServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + OrganizationAddressGroupServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationAddressGroupServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + OrganizationAddressGroupServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationAddressGroupServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == OrganizationAddressGroupServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationAddressGroupServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + OrganizationAddressGroupServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - OrganizationAddressGroupServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + OrganizationAddressGroupServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) def test__get_universe_domain(): client_universe_domain = "foo.com" universe_domain_env = "bar.com" - assert OrganizationAddressGroupServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert OrganizationAddressGroupServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert OrganizationAddressGroupServiceClient._get_universe_domain(None, None) == OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE + assert ( + OrganizationAddressGroupServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + OrganizationAddressGroupServiceClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + OrganizationAddressGroupServiceClient._get_universe_domain(None, None) + == OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: OrganizationAddressGroupServiceClient._get_universe_domain("", None) assert str(excinfo.value) == "Universe Domain cannot be an empty string." -@pytest.mark.parametrize("error_code,cred_info_json,show_cred_info", [ - (401, CRED_INFO_JSON, True), - (403, CRED_INFO_JSON, True), - (404, CRED_INFO_JSON, True), - (500, CRED_INFO_JSON, False), - (401, None, False), - (403, None, False), - (404, None, False), - (500, None, False) -]) + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): cred = mock.Mock(["get_cred_info"]) cred.get_cred_info = mock.Mock(return_value=cred_info_json) @@ -229,7 +408,8 @@ def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_in else: assert error.details == ["foo"] -@pytest.mark.parametrize("error_code", [401,403,404,500]) + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): cred = mock.Mock([]) assert not hasattr(cred, "get_cred_info") @@ -242,14 +422,22 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] -@pytest.mark.parametrize("client_class,transport_name", [ - (OrganizationAddressGroupServiceClient, "grpc"), - (OrganizationAddressGroupServiceAsyncClient, "grpc_asyncio"), - (OrganizationAddressGroupServiceClient, "rest"), -]) -def test_organization_address_group_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (OrganizationAddressGroupServiceClient, "grpc"), + (OrganizationAddressGroupServiceAsyncClient, "grpc_asyncio"), + (OrganizationAddressGroupServiceClient, "rest"), + ], +) +def test_organization_address_group_service_client_from_service_account_info( + client_class, transport_name +): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info, transport=transport_name) @@ -257,52 +445,73 @@ def test_organization_address_group_service_client_from_service_account_info(cli assert isinstance(client, client_class) assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networksecurity.googleapis.com' + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" ) -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.OrganizationAddressGroupServiceGrpcTransport, "grpc"), - (transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.OrganizationAddressGroupServiceRestTransport, "rest"), -]) -def test_organization_address_group_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.OrganizationAddressGroupServiceGrpcTransport, "grpc"), + ( + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (transports.OrganizationAddressGroupServiceRestTransport, "rest"), + ], +) +def test_organization_address_group_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize("client_class,transport_name", [ - (OrganizationAddressGroupServiceClient, "grpc"), - (OrganizationAddressGroupServiceAsyncClient, "grpc_asyncio"), - (OrganizationAddressGroupServiceClient, "rest"), -]) -def test_organization_address_group_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (OrganizationAddressGroupServiceClient, "grpc"), + (OrganizationAddressGroupServiceAsyncClient, "grpc_asyncio"), + (OrganizationAddressGroupServiceClient, "rest"), + ], +) +def test_organization_address_group_service_client_from_service_account_file( + client_class, transport_name +): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) assert client.transport._credentials == creds assert isinstance(client, client_class) - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://networksecurity.googleapis.com' + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" ) @@ -318,30 +527,57 @@ def test_organization_address_group_service_client_get_transport_class(): assert transport == transports.OrganizationAddressGroupServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc"), - (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceRestTransport, "rest"), -]) -@mock.patch.object(OrganizationAddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceClient)) -@mock.patch.object(OrganizationAddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient)) -def test_organization_address_group_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceGrpcTransport, + "grpc", + ), + ( + OrganizationAddressGroupServiceAsyncClient, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + OrganizationAddressGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationAddressGroupServiceClient), +) +@mock.patch.object( + OrganizationAddressGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient), +) +def test_organization_address_group_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(OrganizationAddressGroupServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object( + OrganizationAddressGroupServiceClient, "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(OrganizationAddressGroupServiceClient, 'get_transport_class') as gtc: + with mock.patch.object( + OrganizationAddressGroupServiceClient, "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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( @@ -359,13 +595,15 @@ def test_organization_address_group_service_client_client_options(client_class, # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -377,7 +615,7 @@ def test_organization_address_group_service_client_client_options(client_class, # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -397,23 +635,33 @@ def test_organization_address_group_service_client_client_options(client_class, with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError) as excinfo: client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", @@ -422,48 +670,102 @@ def test_organization_address_group_service_client_client_options(client_class, api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc", "true"), - (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc", "false"), - (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceRestTransport, "rest", "true"), - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(OrganizationAddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceClient)) -@mock.patch.object(OrganizationAddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceGrpcTransport, + "grpc", + "true", + ), + ( + OrganizationAddressGroupServiceAsyncClient, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceGrpcTransport, + "grpc", + "false", + ), + ( + OrganizationAddressGroupServiceAsyncClient, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceRestTransport, + "rest", + "true", + ), + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + OrganizationAddressGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationAddressGroupServiceClient), +) +@mock.patch.object( + OrganizationAddressGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_organization_address_group_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_organization_address_group_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: + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -482,12 +784,22 @@ def test_organization_address_group_service_client_mtls_env_auto(client_class, t # 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): + 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_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -508,15 +820,22 @@ def test_organization_address_group_service_client_mtls_env_auto(client_class, t ) # 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): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -526,19 +845,34 @@ def test_organization_address_group_service_client_mtls_env_auto(client_class, t ) -@pytest.mark.parametrize("client_class", [ - OrganizationAddressGroupServiceClient, OrganizationAddressGroupServiceAsyncClient -]) -@mock.patch.object(OrganizationAddressGroupServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationAddressGroupServiceClient)) -@mock.patch.object(OrganizationAddressGroupServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OrganizationAddressGroupServiceAsyncClient)) -def test_organization_address_group_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", + [OrganizationAddressGroupServiceClient, OrganizationAddressGroupServiceAsyncClient], +) +@mock.patch.object( + OrganizationAddressGroupServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OrganizationAddressGroupServiceClient), +) +@mock.patch.object( + OrganizationAddressGroupServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OrganizationAddressGroupServiceAsyncClient), +) +def test_organization_address_group_service_client_get_mtls_endpoint_and_cert_source( + client_class, +): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source @@ -546,8 +880,12 @@ def test_organization_address_group_service_client_get_mtls_endpoint_and_cert_so with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source is None @@ -565,16 +903,28 @@ def test_organization_address_group_service_client_get_mtls_endpoint_and_cert_so # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -584,34 +934,67 @@ def test_organization_address_group_service_client_get_mtls_endpoint_and_cert_so with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + -@pytest.mark.parametrize("client_class", [ - OrganizationAddressGroupServiceClient, OrganizationAddressGroupServiceAsyncClient -]) -@mock.patch.object(OrganizationAddressGroupServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceClient)) -@mock.patch.object(OrganizationAddressGroupServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", + [OrganizationAddressGroupServiceClient, OrganizationAddressGroupServiceAsyncClient], +) +@mock.patch.object( + OrganizationAddressGroupServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationAddressGroupServiceClient), +) +@mock.patch.object( + OrganizationAddressGroupServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationAddressGroupServiceAsyncClient), +) def test_organization_address_group_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = OrganizationAddressGroupServiceClient._DEFAULT_UNIVERSE - default_endpoint = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ( + OrganizationAddressGroupServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", # use ClientOptions.api_endpoint as the api endpoint regardless. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) assert client.api_endpoint == api_override # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", @@ -634,11 +1017,19 @@ def test_organization_address_group_service_client_client_api_endpoint(client_cl universe_exists = hasattr(options, "universe_domain") if universe_exists: options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. @@ -646,27 +1037,48 @@ def test_organization_address_group_service_client_client_api_endpoint(client_cl if hasattr(options, "universe_domain"): delattr(options, "universe_domain") with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) assert client.api_endpoint == default_endpoint -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc"), - (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceRestTransport, "rest"), -]) -def test_organization_address_group_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceGrpcTransport, + "grpc", + ), + ( + OrganizationAddressGroupServiceAsyncClient, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceRestTransport, + "rest", + ), + ], +) +def test_organization_address_group_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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, @@ -675,24 +1087,45 @@ def test_organization_address_group_service_client_client_options_scopes(client_ api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc", grpc_helpers), - (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceRestTransport, "rest", None), -]) -def test_organization_address_group_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + OrganizationAddressGroupServiceAsyncClient, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceRestTransport, + "rest", + None, + ), + ], +) +def test_organization_address_group_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -701,11 +1134,14 @@ def test_organization_address_group_service_client_client_options_credentials_fi api_audience=None, ) + def test_organization_address_group_service_client_client_options_from_dict(): - with mock.patch('google.cloud.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.cloud.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = OrganizationAddressGroupServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -720,23 +1156,38 @@ def test_organization_address_group_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport, "grpc", grpc_helpers), - (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_organization_address_group_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + OrganizationAddressGroupServiceAsyncClient, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_organization_address_group_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -763,9 +1214,7 @@ def test_organization_address_group_service_client_create_channel_credentials_fi credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=None, default_host="networksecurity.googleapis.com", ssl_credentials=None, @@ -776,11 +1225,14 @@ def test_organization_address_group_service_client_create_channel_credentials_fi ) -@pytest.mark.parametrize("request_type", [ - address_group.ListAddressGroupsRequest, - dict, -]) -def test_list_address_groups(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + address_group.ListAddressGroupsRequest, + dict, + ], +) +def test_list_address_groups(request_type, transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -792,12 +1244,12 @@ def test_list_address_groups(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.ListAddressGroupsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) response = client.list_address_groups(request) @@ -809,8 +1261,8 @@ def test_list_address_groups(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] def test_list_address_groups_non_empty_request_with_auto_populated_field(): @@ -818,30 +1270,33 @@ def test_list_address_groups_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = address_group.ListAddressGroupsRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_address_groups), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_address_groups(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == address_group.ListAddressGroupsRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_address_groups_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -856,12 +1311,18 @@ def test_list_address_groups_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_address_groups in client._transport._wrapped_methods + assert ( + client._transport.list_address_groups in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_address_groups] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_address_groups + ] = mock_rpc request = {} client.list_address_groups(request) @@ -874,8 +1335,11 @@ def test_list_address_groups_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_address_groups_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_address_groups_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -889,12 +1353,17 @@ async def test_list_address_groups_async_use_cached_wrapped_rpc(transport: str = wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_address_groups in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_address_groups + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_address_groups] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_address_groups + ] = mock_rpc request = {} await client.list_address_groups(request) @@ -908,8 +1377,11 @@ async def test_list_address_groups_async_use_cached_wrapped_rpc(transport: str = assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_address_groups_async(transport: str = 'grpc_asyncio', request_type=address_group.ListAddressGroupsRequest): +async def test_list_address_groups_async( + transport: str = "grpc_asyncio", request_type=address_group.ListAddressGroupsRequest +): client = OrganizationAddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -921,13 +1393,15 @@ async def test_list_address_groups_async(transport: str = 'grpc_asyncio', reques # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.ListAddressGroupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) response = await client.list_address_groups(request) # Establish that the underlying gRPC stub method was called. @@ -938,14 +1412,15 @@ async def test_list_address_groups_async(transport: str = 'grpc_asyncio', reques # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio async def test_list_address_groups_async_from_dict(): await test_list_address_groups_async(request_type=dict) + def test_list_address_groups_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -955,12 +1430,12 @@ def test_list_address_groups_field_headers(): # a field header. Set these to a non-empty value. request = address_group.ListAddressGroupsRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: call.return_value = address_group.ListAddressGroupsResponse() client.list_address_groups(request) @@ -972,9 +1447,9 @@ def test_list_address_groups_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -987,13 +1462,15 @@ async def test_list_address_groups_field_headers_async(): # a field header. Set these to a non-empty value. request = address_group.ListAddressGroupsRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse()) + type(client.transport.list_address_groups), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.ListAddressGroupsResponse() + ) await client.list_address_groups(request) # Establish that the underlying gRPC stub method was called. @@ -1004,9 +1481,9 @@ async def test_list_address_groups_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_list_address_groups_flattened(): @@ -1016,14 +1493,14 @@ def test_list_address_groups_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.ListAddressGroupsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_address_groups( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1031,7 +1508,7 @@ def test_list_address_groups_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val @@ -1045,9 +1522,10 @@ def test_list_address_groups_flattened_error(): with pytest.raises(ValueError): client.list_address_groups( address_group.ListAddressGroupsRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_address_groups_flattened_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -1056,16 +1534,18 @@ async def test_list_address_groups_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.ListAddressGroupsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.ListAddressGroupsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_address_groups( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1073,9 +1553,10 @@ async def test_list_address_groups_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val + @pytest.mark.asyncio async def test_list_address_groups_flattened_error_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -1087,7 +1568,7 @@ async def test_list_address_groups_flattened_error_async(): with pytest.raises(ValueError): await client.list_address_groups( address_group.ListAddressGroupsRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1099,8 +1580,8 @@ def test_list_address_groups_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( address_group.ListAddressGroupsResponse( @@ -1109,17 +1590,17 @@ def test_list_address_groups_pager(transport_name: str = "grpc"): address_group.AddressGroup(), address_group.AddressGroup(), ], - next_page_token='abc', + next_page_token="abc", ), address_group.ListAddressGroupsResponse( address_groups=[], - next_page_token='def', + next_page_token="def", ), address_group.ListAddressGroupsResponse( address_groups=[ address_group.AddressGroup(), ], - next_page_token='ghi', + next_page_token="ghi", ), address_group.ListAddressGroupsResponse( address_groups=[ @@ -1134,9 +1615,7 @@ def test_list_address_groups_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) pager = client.list_address_groups(request={}, retry=retry, timeout=timeout) @@ -1146,8 +1625,9 @@ def test_list_address_groups_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, address_group.AddressGroup) - for i in results) + assert all(isinstance(i, address_group.AddressGroup) for i in results) + + def test_list_address_groups_pages(transport_name: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1156,8 +1636,8 @@ def test_list_address_groups_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( address_group.ListAddressGroupsResponse( @@ -1166,17 +1646,17 @@ def test_list_address_groups_pages(transport_name: str = "grpc"): address_group.AddressGroup(), address_group.AddressGroup(), ], - next_page_token='abc', + next_page_token="abc", ), address_group.ListAddressGroupsResponse( address_groups=[], - next_page_token='def', + next_page_token="def", ), address_group.ListAddressGroupsResponse( address_groups=[ address_group.AddressGroup(), ], - next_page_token='ghi', + next_page_token="ghi", ), address_group.ListAddressGroupsResponse( address_groups=[ @@ -1187,9 +1667,10 @@ def test_list_address_groups_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_address_groups(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token + @pytest.mark.asyncio async def test_list_address_groups_async_pager(): client = OrganizationAddressGroupServiceAsyncClient( @@ -1198,8 +1679,10 @@ async def test_list_address_groups_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_address_groups), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( address_group.ListAddressGroupsResponse( @@ -1208,17 +1691,17 @@ async def test_list_address_groups_async_pager(): address_group.AddressGroup(), address_group.AddressGroup(), ], - next_page_token='abc', + next_page_token="abc", ), address_group.ListAddressGroupsResponse( address_groups=[], - next_page_token='def', + next_page_token="def", ), address_group.ListAddressGroupsResponse( address_groups=[ address_group.AddressGroup(), ], - next_page_token='ghi', + next_page_token="ghi", ), address_group.ListAddressGroupsResponse( address_groups=[ @@ -1228,15 +1711,16 @@ async def test_list_address_groups_async_pager(): ), RuntimeError, ) - async_pager = await client.list_address_groups(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_address_groups( + request={}, + ) + assert async_pager.next_page_token == "abc" responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, address_group.AddressGroup) - for i in responses) + assert all(isinstance(i, address_group.AddressGroup) for i in responses) @pytest.mark.asyncio @@ -1247,8 +1731,10 @@ async def test_list_address_groups_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_address_groups), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( address_group.ListAddressGroupsResponse( @@ -1257,17 +1743,17 @@ async def test_list_address_groups_async_pages(): address_group.AddressGroup(), address_group.AddressGroup(), ], - next_page_token='abc', + next_page_token="abc", ), address_group.ListAddressGroupsResponse( address_groups=[], - next_page_token='def', + next_page_token="def", ), address_group.ListAddressGroupsResponse( address_groups=[ address_group.AddressGroup(), ], - next_page_token='ghi', + next_page_token="ghi", ), address_group.ListAddressGroupsResponse( address_groups=[ @@ -1280,18 +1766,22 @@ async def test_list_address_groups_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_address_groups(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize("request_type", [ - address_group.GetAddressGroupRequest, - dict, -]) -def test_get_address_group(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + address_group.GetAddressGroupRequest, + dict, + ], +) +def test_get_address_group(request_type, transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1303,16 +1793,16 @@ def test_get_address_group(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.AddressGroup( - name='name_value', - description='description_value', + name="name_value", + description="description_value", type_=address_group.AddressGroup.Type.IPV4, - items=['items_value'], + items=["items_value"], capacity=846, - self_link='self_link_value', + self_link="self_link_value", purpose=[address_group.AddressGroup.Purpose.DEFAULT], ) response = client.get_address_group(request) @@ -1325,12 +1815,12 @@ def test_get_address_group(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, address_group.AddressGroup) - assert response.name == 'name_value' - assert response.description == 'description_value' + assert response.name == "name_value" + assert response.description == "description_value" assert response.type_ == address_group.AddressGroup.Type.IPV4 - assert response.items == ['items_value'] + assert response.items == ["items_value"] assert response.capacity == 846 - assert response.self_link == 'self_link_value' + assert response.self_link == "self_link_value" assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] @@ -1339,28 +1829,31 @@ def test_get_address_group_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = address_group.GetAddressGroupRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_address_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_address_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == address_group.GetAddressGroupRequest( - name='name_value', + name="name_value", ) + def test_get_address_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1379,8 +1872,12 @@ def test_get_address_group_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_address_group + ] = mock_rpc request = {} client.get_address_group(request) @@ -1393,8 +1890,11 @@ def test_get_address_group_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_address_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1408,12 +1908,17 @@ async def test_get_address_group_async_use_cached_wrapped_rpc(transport: str = " wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_address_group in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_address_group + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_address_group] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_address_group + ] = mock_rpc request = {} await client.get_address_group(request) @@ -1427,8 +1932,11 @@ async def test_get_address_group_async_use_cached_wrapped_rpc(transport: str = " assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_address_group_async(transport: str = 'grpc_asyncio', request_type=address_group.GetAddressGroupRequest): +async def test_get_address_group_async( + transport: str = "grpc_asyncio", request_type=address_group.GetAddressGroupRequest +): client = OrganizationAddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1440,18 +1948,20 @@ async def test_get_address_group_async(transport: str = 'grpc_asyncio', request_ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup( - name='name_value', - description='description_value', - type_=address_group.AddressGroup.Type.IPV4, - items=['items_value'], - capacity=846, - self_link='self_link_value', - purpose=[address_group.AddressGroup.Purpose.DEFAULT], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.AddressGroup( + name="name_value", + description="description_value", + type_=address_group.AddressGroup.Type.IPV4, + items=["items_value"], + capacity=846, + self_link="self_link_value", + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + ) + ) response = await client.get_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1462,12 +1972,12 @@ async def test_get_address_group_async(transport: str = 'grpc_asyncio', request_ # Establish that the response is the type that we expect. assert isinstance(response, address_group.AddressGroup) - assert response.name == 'name_value' - assert response.description == 'description_value' + assert response.name == "name_value" + assert response.description == "description_value" assert response.type_ == address_group.AddressGroup.Type.IPV4 - assert response.items == ['items_value'] + assert response.items == ["items_value"] assert response.capacity == 846 - assert response.self_link == 'self_link_value' + assert response.self_link == "self_link_value" assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] @@ -1475,6 +1985,7 @@ async def test_get_address_group_async(transport: str = 'grpc_asyncio', request_ async def test_get_address_group_async_from_dict(): await test_get_address_group_async(request_type=dict) + def test_get_address_group_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1484,12 +1995,12 @@ def test_get_address_group_field_headers(): # a field header. Set these to a non-empty value. request = address_group.GetAddressGroupRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: call.return_value = address_group.AddressGroup() client.get_address_group(request) @@ -1501,9 +2012,9 @@ def test_get_address_group_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1516,13 +2027,15 @@ async def test_get_address_group_field_headers_async(): # a field header. Set these to a non-empty value. request = address_group.GetAddressGroupRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup()) + type(client.transport.get_address_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.AddressGroup() + ) await client.get_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1533,9 +2046,9 @@ async def test_get_address_group_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_address_group_flattened(): @@ -1545,14 +2058,14 @@ def test_get_address_group_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.AddressGroup() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_address_group( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1560,7 +2073,7 @@ def test_get_address_group_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -1574,9 +2087,10 @@ def test_get_address_group_flattened_error(): with pytest.raises(ValueError): client.get_address_group( address_group.GetAddressGroupRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_address_group_flattened_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -1585,16 +2099,18 @@ async def test_get_address_group_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = address_group.AddressGroup() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.AddressGroup() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_address_group( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1602,9 +2118,10 @@ async def test_get_address_group_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_address_group_flattened_error_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -1616,15 +2133,18 @@ async def test_get_address_group_flattened_error_async(): with pytest.raises(ValueError): await client.get_address_group( address_group.GetAddressGroupRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.CreateAddressGroupRequest, - dict, -]) -def test_create_address_group(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.CreateAddressGroupRequest, + dict, + ], +) +def test_create_address_group(request_type, transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1636,10 +2156,10 @@ def test_create_address_group(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.create_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1657,32 +2177,35 @@ def test_create_address_group_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.CreateAddressGroupRequest( - parent='parent_value', - address_group_id='address_group_id_value', - request_id='request_id_value', + parent="parent_value", + address_group_id="address_group_id_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.create_address_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_address_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.CreateAddressGroupRequest( - parent='parent_value', - address_group_id='address_group_id_value', - request_id='request_id_value', + parent="parent_value", + address_group_id="address_group_id_value", + request_id="request_id_value", ) + def test_create_address_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1697,12 +2220,18 @@ def test_create_address_group_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_address_group in client._transport._wrapped_methods + assert ( + client._transport.create_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_address_group + ] = mock_rpc request = {} client.create_address_group(request) @@ -1720,8 +2249,11 @@ def test_create_address_group_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_address_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -1735,12 +2267,17 @@ async def test_create_address_group_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.create_address_group in client._client._transport._wrapped_methods + assert ( + client._client._transport.create_address_group + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_address_group] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.create_address_group + ] = mock_rpc request = {} await client.create_address_group(request) @@ -1759,8 +2296,12 @@ async def test_create_address_group_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_address_group_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.CreateAddressGroupRequest): +async def test_create_address_group_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.CreateAddressGroupRequest, +): client = OrganizationAddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1772,11 +2313,11 @@ async def test_create_address_group_async(transport: str = 'grpc_asyncio', reque # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.create_address_group(request) @@ -1794,6 +2335,7 @@ async def test_create_address_group_async(transport: str = 'grpc_asyncio', reque async def test_create_address_group_async_from_dict(): await test_create_address_group_async(request_type=dict) + def test_create_address_group_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1803,13 +2345,13 @@ def test_create_address_group_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.CreateAddressGroupRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.create_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.create_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1820,9 +2362,9 @@ def test_create_address_group_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1835,13 +2377,15 @@ async def test_create_address_group_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.CreateAddressGroupRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.create_address_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.create_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1852,9 +2396,9 @@ async def test_create_address_group_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_create_address_group_flattened(): @@ -1864,16 +2408,16 @@ def test_create_address_group_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_address_group( - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) # Establish that the underlying call was made with the expected @@ -1881,13 +2425,13 @@ def test_create_address_group_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].address_group - mock_val = gcn_address_group.AddressGroup(name='name_value') + mock_val = gcn_address_group.AddressGroup(name="name_value") assert arg == mock_val arg = args[0].address_group_id - mock_val = 'address_group_id_value' + mock_val = "address_group_id_value" assert arg == mock_val @@ -1901,11 +2445,12 @@ def test_create_address_group_flattened_error(): with pytest.raises(ValueError): client.create_address_group( gcn_address_group.CreateAddressGroupRequest(), - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) + @pytest.mark.asyncio async def test_create_address_group_flattened_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -1914,20 +2459,20 @@ async def test_create_address_group_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_address_group( - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) # Establish that the underlying call was made with the expected @@ -1935,15 +2480,16 @@ async def test_create_address_group_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].address_group - mock_val = gcn_address_group.AddressGroup(name='name_value') + mock_val = gcn_address_group.AddressGroup(name="name_value") assert arg == mock_val arg = args[0].address_group_id - mock_val = 'address_group_id_value' + mock_val = "address_group_id_value" assert arg == mock_val + @pytest.mark.asyncio async def test_create_address_group_flattened_error_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -1955,17 +2501,20 @@ async def test_create_address_group_flattened_error_async(): with pytest.raises(ValueError): await client.create_address_group( gcn_address_group.CreateAddressGroupRequest(), - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.UpdateAddressGroupRequest, - dict, -]) -def test_update_address_group(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.UpdateAddressGroupRequest, + dict, + ], +) +def test_update_address_group(request_type, transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1977,10 +2526,10 @@ def test_update_address_group(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.update_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -1998,28 +2547,31 @@ def test_update_address_group_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.UpdateAddressGroupRequest( - request_id='request_id_value', + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.update_address_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_address_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.UpdateAddressGroupRequest( - request_id='request_id_value', + request_id="request_id_value", ) + def test_update_address_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2034,12 +2586,18 @@ def test_update_address_group_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_address_group in client._transport._wrapped_methods + assert ( + client._transport.update_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_address_group + ] = mock_rpc request = {} client.update_address_group(request) @@ -2057,8 +2615,11 @@ def test_update_address_group_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_address_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2072,12 +2633,17 @@ async def test_update_address_group_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_address_group in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_address_group + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_address_group] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_address_group + ] = mock_rpc request = {} await client.update_address_group(request) @@ -2096,8 +2662,12 @@ async def test_update_address_group_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_address_group_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.UpdateAddressGroupRequest): +async def test_update_address_group_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.UpdateAddressGroupRequest, +): client = OrganizationAddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2109,11 +2679,11 @@ async def test_update_address_group_async(transport: str = 'grpc_asyncio', reque # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.update_address_group(request) @@ -2131,6 +2701,7 @@ async def test_update_address_group_async(transport: str = 'grpc_asyncio', reque async def test_update_address_group_async_from_dict(): await test_update_address_group_async(request_type=dict) + def test_update_address_group_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2140,13 +2711,13 @@ def test_update_address_group_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.UpdateAddressGroupRequest() - request.address_group.name = 'name_value' + request.address_group.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.update_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.update_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -2157,9 +2728,9 @@ def test_update_address_group_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2172,13 +2743,15 @@ async def test_update_address_group_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.UpdateAddressGroupRequest() - request.address_group.name = 'name_value' + request.address_group.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.update_address_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.update_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -2189,9 +2762,9 @@ async def test_update_address_group_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group.name=name_value", + ) in kw["metadata"] def test_update_address_group_flattened(): @@ -2201,15 +2774,15 @@ def test_update_address_group_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_address_group( - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -2217,10 +2790,10 @@ def test_update_address_group_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = gcn_address_group.AddressGroup(name='name_value') + mock_val = gcn_address_group.AddressGroup(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -2234,10 +2807,11 @@ def test_update_address_group_flattened_error(): with pytest.raises(ValueError): client.update_address_group( gcn_address_group.UpdateAddressGroupRequest(), - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_address_group_flattened_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -2246,19 +2820,19 @@ async def test_update_address_group_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_address_group( - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -2266,12 +2840,13 @@ async def test_update_address_group_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = gcn_address_group.AddressGroup(name='name_value') + mock_val = gcn_address_group.AddressGroup(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_address_group_flattened_error_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -2283,16 +2858,19 @@ async def test_update_address_group_flattened_error_async(): with pytest.raises(ValueError): await client.update_address_group( gcn_address_group.UpdateAddressGroupRequest(), - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.AddAddressGroupItemsRequest, - dict, -]) -def test_add_address_group_items(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.AddAddressGroupItemsRequest, + dict, + ], +) +def test_add_address_group_items(request_type, transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2304,10 +2882,10 @@ def test_add_address_group_items(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.add_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2325,30 +2903,33 @@ def test_add_address_group_items_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.AddAddressGroupItemsRequest( - address_group='address_group_value', - request_id='request_id_value', + address_group="address_group_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.add_address_group_items), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.add_address_group_items(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.AddAddressGroupItemsRequest( - address_group='address_group_value', - request_id='request_id_value', + address_group="address_group_value", + request_id="request_id_value", ) + def test_add_address_group_items_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2363,12 +2944,19 @@ def test_add_address_group_items_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.add_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.add_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.add_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.add_address_group_items + ] = mock_rpc request = {} client.add_address_group_items(request) @@ -2386,8 +2974,11 @@ def test_add_address_group_items_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_add_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_add_address_group_items_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2401,12 +2992,17 @@ async def test_add_address_group_items_async_use_cached_wrapped_rpc(transport: s wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.add_address_group_items in client._client._transport._wrapped_methods + assert ( + client._client._transport.add_address_group_items + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.add_address_group_items] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.add_address_group_items + ] = mock_rpc request = {} await client.add_address_group_items(request) @@ -2425,8 +3021,12 @@ async def test_add_address_group_items_async_use_cached_wrapped_rpc(transport: s assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_add_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.AddAddressGroupItemsRequest): +async def test_add_address_group_items_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.AddAddressGroupItemsRequest, +): client = OrganizationAddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2438,11 +3038,11 @@ async def test_add_address_group_items_async(transport: str = 'grpc_asyncio', re # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.add_address_group_items(request) @@ -2460,6 +3060,7 @@ async def test_add_address_group_items_async(transport: str = 'grpc_asyncio', re async def test_add_address_group_items_async_from_dict(): await test_add_address_group_items_async(request_type=dict) + def test_add_address_group_items_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2469,13 +3070,13 @@ def test_add_address_group_items_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.AddAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.add_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.add_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2486,9 +3087,9 @@ def test_add_address_group_items_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2501,13 +3102,15 @@ async def test_add_address_group_items_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.AddAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.add_address_group_items), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.add_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2518,9 +3121,9 @@ async def test_add_address_group_items_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] def test_add_address_group_items_flattened(): @@ -2530,15 +3133,15 @@ def test_add_address_group_items_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.add_address_group_items( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) # Establish that the underlying call was made with the expected @@ -2546,10 +3149,10 @@ def test_add_address_group_items_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].items - mock_val = ['items_value'] + mock_val = ["items_value"] assert arg == mock_val @@ -2563,10 +3166,11 @@ def test_add_address_group_items_flattened_error(): with pytest.raises(ValueError): client.add_address_group_items( gcn_address_group.AddAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) + @pytest.mark.asyncio async def test_add_address_group_items_flattened_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -2575,19 +3179,19 @@ async def test_add_address_group_items_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.add_address_group_items( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) # Establish that the underlying call was made with the expected @@ -2595,12 +3199,13 @@ async def test_add_address_group_items_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].items - mock_val = ['items_value'] + mock_val = ["items_value"] assert arg == mock_val + @pytest.mark.asyncio async def test_add_address_group_items_flattened_error_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -2612,16 +3217,19 @@ async def test_add_address_group_items_flattened_error_async(): with pytest.raises(ValueError): await client.add_address_group_items( gcn_address_group.AddAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.RemoveAddressGroupItemsRequest, - dict, -]) -def test_remove_address_group_items(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.RemoveAddressGroupItemsRequest, + dict, + ], +) +def test_remove_address_group_items(request_type, transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2633,10 +3241,10 @@ def test_remove_address_group_items(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.remove_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2654,30 +3262,33 @@ def test_remove_address_group_items_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.RemoveAddressGroupItemsRequest( - address_group='address_group_value', - request_id='request_id_value', + address_group="address_group_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.remove_address_group_items), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.remove_address_group_items(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.RemoveAddressGroupItemsRequest( - address_group='address_group_value', - request_id='request_id_value', + address_group="address_group_value", + request_id="request_id_value", ) + def test_remove_address_group_items_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2692,12 +3303,19 @@ def test_remove_address_group_items_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.remove_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.remove_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.remove_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.remove_address_group_items + ] = mock_rpc request = {} client.remove_address_group_items(request) @@ -2715,8 +3333,11 @@ def test_remove_address_group_items_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_remove_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_remove_address_group_items_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -2730,12 +3351,17 @@ async def test_remove_address_group_items_async_use_cached_wrapped_rpc(transport wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.remove_address_group_items in client._client._transport._wrapped_methods + assert ( + client._client._transport.remove_address_group_items + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.remove_address_group_items] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.remove_address_group_items + ] = mock_rpc request = {} await client.remove_address_group_items(request) @@ -2754,8 +3380,12 @@ async def test_remove_address_group_items_async_use_cached_wrapped_rpc(transport assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_remove_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.RemoveAddressGroupItemsRequest): +async def test_remove_address_group_items_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.RemoveAddressGroupItemsRequest, +): client = OrganizationAddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2767,11 +3397,11 @@ async def test_remove_address_group_items_async(transport: str = 'grpc_asyncio', # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.remove_address_group_items(request) @@ -2789,6 +3419,7 @@ async def test_remove_address_group_items_async(transport: str = 'grpc_asyncio', async def test_remove_address_group_items_async_from_dict(): await test_remove_address_group_items_async(request_type=dict) + def test_remove_address_group_items_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2798,13 +3429,13 @@ def test_remove_address_group_items_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.RemoveAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.remove_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.remove_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2815,9 +3446,9 @@ def test_remove_address_group_items_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2830,13 +3461,15 @@ async def test_remove_address_group_items_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.RemoveAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.remove_address_group_items), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.remove_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2847,9 +3480,9 @@ async def test_remove_address_group_items_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] def test_remove_address_group_items_flattened(): @@ -2859,15 +3492,15 @@ def test_remove_address_group_items_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.remove_address_group_items( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) # Establish that the underlying call was made with the expected @@ -2875,10 +3508,10 @@ def test_remove_address_group_items_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].items - mock_val = ['items_value'] + mock_val = ["items_value"] assert arg == mock_val @@ -2892,10 +3525,11 @@ def test_remove_address_group_items_flattened_error(): with pytest.raises(ValueError): client.remove_address_group_items( gcn_address_group.RemoveAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) + @pytest.mark.asyncio async def test_remove_address_group_items_flattened_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -2904,19 +3538,19 @@ async def test_remove_address_group_items_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.remove_address_group_items( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) # Establish that the underlying call was made with the expected @@ -2924,12 +3558,13 @@ async def test_remove_address_group_items_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].items - mock_val = ['items_value'] + mock_val = ["items_value"] assert arg == mock_val + @pytest.mark.asyncio async def test_remove_address_group_items_flattened_error_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -2941,16 +3576,19 @@ async def test_remove_address_group_items_flattened_error_async(): with pytest.raises(ValueError): await client.remove_address_group_items( gcn_address_group.RemoveAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.CloneAddressGroupItemsRequest, - dict, -]) -def test_clone_address_group_items(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.CloneAddressGroupItemsRequest, + dict, + ], +) +def test_clone_address_group_items(request_type, transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2962,10 +3600,10 @@ def test_clone_address_group_items(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.clone_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -2983,32 +3621,35 @@ def test_clone_address_group_items_non_empty_request_with_auto_populated_field() # automatically populated, according to AIP-4235, with non-empty requests. client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.CloneAddressGroupItemsRequest( - address_group='address_group_value', - source_address_group='source_address_group_value', - request_id='request_id_value', + address_group="address_group_value", + source_address_group="source_address_group_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.clone_address_group_items), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.clone_address_group_items(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.CloneAddressGroupItemsRequest( - address_group='address_group_value', - source_address_group='source_address_group_value', - request_id='request_id_value', + address_group="address_group_value", + source_address_group="source_address_group_value", + request_id="request_id_value", ) + def test_clone_address_group_items_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3023,12 +3664,19 @@ def test_clone_address_group_items_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.clone_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.clone_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.clone_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.clone_address_group_items + ] = mock_rpc request = {} client.clone_address_group_items(request) @@ -3046,8 +3694,11 @@ def test_clone_address_group_items_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_clone_address_group_items_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_clone_address_group_items_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3061,12 +3712,17 @@ async def test_clone_address_group_items_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.clone_address_group_items in client._client._transport._wrapped_methods + assert ( + client._client._transport.clone_address_group_items + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.clone_address_group_items] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.clone_address_group_items + ] = mock_rpc request = {} await client.clone_address_group_items(request) @@ -3085,8 +3741,12 @@ async def test_clone_address_group_items_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_clone_address_group_items_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.CloneAddressGroupItemsRequest): +async def test_clone_address_group_items_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.CloneAddressGroupItemsRequest, +): client = OrganizationAddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3098,11 +3758,11 @@ async def test_clone_address_group_items_async(transport: str = 'grpc_asyncio', # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.clone_address_group_items(request) @@ -3120,6 +3780,7 @@ async def test_clone_address_group_items_async(transport: str = 'grpc_asyncio', async def test_clone_address_group_items_async_from_dict(): await test_clone_address_group_items_async(request_type=dict) + def test_clone_address_group_items_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3129,13 +3790,13 @@ def test_clone_address_group_items_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.CloneAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.clone_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.clone_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -3146,9 +3807,9 @@ def test_clone_address_group_items_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -3161,13 +3822,15 @@ async def test_clone_address_group_items_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.CloneAddressGroupItemsRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.clone_address_group_items), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.clone_address_group_items(request) # Establish that the underlying gRPC stub method was called. @@ -3178,9 +3841,9 @@ async def test_clone_address_group_items_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] def test_clone_address_group_items_flattened(): @@ -3190,15 +3853,15 @@ def test_clone_address_group_items_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.clone_address_group_items( - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) # Establish that the underlying call was made with the expected @@ -3206,10 +3869,10 @@ def test_clone_address_group_items_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].source_address_group - mock_val = 'source_address_group_value' + mock_val = "source_address_group_value" assert arg == mock_val @@ -3223,10 +3886,11 @@ def test_clone_address_group_items_flattened_error(): with pytest.raises(ValueError): client.clone_address_group_items( gcn_address_group.CloneAddressGroupItemsRequest(), - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) + @pytest.mark.asyncio async def test_clone_address_group_items_flattened_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -3235,19 +3899,19 @@ async def test_clone_address_group_items_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.clone_address_group_items( - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) # Establish that the underlying call was made with the expected @@ -3255,12 +3919,13 @@ async def test_clone_address_group_items_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val arg = args[0].source_address_group - mock_val = 'source_address_group_value' + mock_val = "source_address_group_value" assert arg == mock_val + @pytest.mark.asyncio async def test_clone_address_group_items_flattened_error_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -3272,16 +3937,19 @@ async def test_clone_address_group_items_flattened_error_async(): with pytest.raises(ValueError): await client.clone_address_group_items( gcn_address_group.CloneAddressGroupItemsRequest(), - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) -@pytest.mark.parametrize("request_type", [ - address_group.DeleteAddressGroupRequest, - dict, -]) -def test_delete_address_group(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + address_group.DeleteAddressGroupRequest, + dict, + ], +) +def test_delete_address_group(request_type, transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3293,10 +3961,10 @@ def test_delete_address_group(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.delete_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -3314,30 +3982,33 @@ def test_delete_address_group_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = address_group.DeleteAddressGroupRequest( - name='name_value', - request_id='request_id_value', + name="name_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.delete_address_group), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.delete_address_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == address_group.DeleteAddressGroupRequest( - name='name_value', - request_id='request_id_value', + name="name_value", + request_id="request_id_value", ) + def test_delete_address_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3352,12 +4023,18 @@ def test_delete_address_group_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_address_group in client._transport._wrapped_methods + assert ( + client._transport.delete_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_address_group + ] = mock_rpc request = {} client.delete_address_group(request) @@ -3375,8 +4052,11 @@ def test_delete_address_group_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_address_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_address_group_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3390,12 +4070,17 @@ async def test_delete_address_group_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.delete_address_group in client._client._transport._wrapped_methods + assert ( + client._client._transport.delete_address_group + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_address_group] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.delete_address_group + ] = mock_rpc request = {} await client.delete_address_group(request) @@ -3414,8 +4099,12 @@ async def test_delete_address_group_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_address_group_async(transport: str = 'grpc_asyncio', request_type=address_group.DeleteAddressGroupRequest): +async def test_delete_address_group_async( + transport: str = "grpc_asyncio", + request_type=address_group.DeleteAddressGroupRequest, +): client = OrganizationAddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3427,11 +4116,11 @@ async def test_delete_address_group_async(transport: str = 'grpc_asyncio', reque # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.delete_address_group(request) @@ -3449,6 +4138,7 @@ async def test_delete_address_group_async(transport: str = 'grpc_asyncio', reque async def test_delete_address_group_async_from_dict(): await test_delete_address_group_async(request_type=dict) + def test_delete_address_group_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3458,13 +4148,13 @@ def test_delete_address_group_field_headers(): # a field header. Set these to a non-empty value. request = address_group.DeleteAddressGroupRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.delete_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.delete_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -3475,9 +4165,9 @@ def test_delete_address_group_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -3490,13 +4180,15 @@ async def test_delete_address_group_field_headers_async(): # a field header. Set these to a non-empty value. request = address_group.DeleteAddressGroupRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.delete_address_group), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.delete_address_group(request) # Establish that the underlying gRPC stub method was called. @@ -3507,9 +4199,9 @@ async def test_delete_address_group_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_delete_address_group_flattened(): @@ -3519,14 +4211,14 @@ def test_delete_address_group_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_address_group( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -3534,7 +4226,7 @@ def test_delete_address_group_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -3548,9 +4240,10 @@ def test_delete_address_group_flattened_error(): with pytest.raises(ValueError): client.delete_address_group( address_group.DeleteAddressGroupRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_address_group_flattened_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -3559,18 +4252,18 @@ async def test_delete_address_group_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_address_group( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -3578,9 +4271,10 @@ async def test_delete_address_group_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_delete_address_group_flattened_error_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -3592,15 +4286,18 @@ async def test_delete_address_group_flattened_error_async(): with pytest.raises(ValueError): await client.delete_address_group( address_group.DeleteAddressGroupRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.ListAddressGroupReferencesRequest, - dict, -]) -def test_list_address_group_references(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.ListAddressGroupReferencesRequest, + dict, + ], +) +def test_list_address_group_references(request_type, transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3612,11 +4309,11 @@ def test_list_address_group_references(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gcn_address_group.ListAddressGroupReferencesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_address_group_references(request) @@ -3628,7 +4325,7 @@ def test_list_address_group_references(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupReferencesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_address_group_references_non_empty_request_with_auto_populated_field(): @@ -3636,30 +4333,33 @@ def test_list_address_group_references_non_empty_request_with_auto_populated_fie # automatically populated, according to AIP-4235, with non-empty requests. client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. request = gcn_address_group.ListAddressGroupReferencesRequest( - address_group='address_group_value', - page_token='page_token_value', + address_group="address_group_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_address_group_references), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_address_group_references(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gcn_address_group.ListAddressGroupReferencesRequest( - address_group='address_group_value', - page_token='page_token_value', + address_group="address_group_value", + page_token="page_token_value", ) + def test_list_address_group_references_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -3674,12 +4374,19 @@ def test_list_address_group_references_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_address_group_references in client._transport._wrapped_methods + assert ( + client._transport.list_address_group_references + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_address_group_references] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_address_group_references + ] = mock_rpc request = {} client.list_address_group_references(request) @@ -3692,8 +4399,11 @@ def test_list_address_group_references_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_address_group_references_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_address_group_references_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -3707,12 +4417,17 @@ async def test_list_address_group_references_async_use_cached_wrapped_rpc(transp wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_address_group_references in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_address_group_references + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_address_group_references] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_address_group_references + ] = mock_rpc request = {} await client.list_address_group_references(request) @@ -3726,8 +4441,12 @@ async def test_list_address_group_references_async_use_cached_wrapped_rpc(transp assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_address_group_references_async(transport: str = 'grpc_asyncio', request_type=gcn_address_group.ListAddressGroupReferencesRequest): +async def test_list_address_group_references_async( + transport: str = "grpc_asyncio", + request_type=gcn_address_group.ListAddressGroupReferencesRequest, +): client = OrganizationAddressGroupServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3739,12 +4458,14 @@ async def test_list_address_group_references_async(transport: str = 'grpc_asynci # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_address_group_references(request) # Establish that the underlying gRPC stub method was called. @@ -3755,13 +4476,14 @@ async def test_list_address_group_references_async(transport: str = 'grpc_asynci # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupReferencesAsyncPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio async def test_list_address_group_references_async_from_dict(): await test_list_address_group_references_async(request_type=dict) + def test_list_address_group_references_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3771,12 +4493,12 @@ def test_list_address_group_references_field_headers(): # a field header. Set these to a non-empty value. request = gcn_address_group.ListAddressGroupReferencesRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() client.list_address_group_references(request) @@ -3788,9 +4510,9 @@ def test_list_address_group_references_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -3803,13 +4525,15 @@ async def test_list_address_group_references_field_headers_async(): # a field header. Set these to a non-empty value. request = gcn_address_group.ListAddressGroupReferencesRequest() - request.address_group = 'address_group_value' + request.address_group = "address_group_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse()) + type(client.transport.list_address_group_references), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcn_address_group.ListAddressGroupReferencesResponse() + ) await client.list_address_group_references(request) # Establish that the underlying gRPC stub method was called. @@ -3820,9 +4544,9 @@ async def test_list_address_group_references_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'address_group=address_group_value', - ) in kw['metadata'] + "x-goog-request-params", + "address_group=address_group_value", + ) in kw["metadata"] def test_list_address_group_references_flattened(): @@ -3832,14 +4556,14 @@ def test_list_address_group_references_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_address_group_references( - address_group='address_group_value', + address_group="address_group_value", ) # Establish that the underlying call was made with the expected @@ -3847,7 +4571,7 @@ def test_list_address_group_references_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val @@ -3861,9 +4585,10 @@ def test_list_address_group_references_flattened_error(): with pytest.raises(ValueError): client.list_address_group_references( gcn_address_group.ListAddressGroupReferencesRequest(), - address_group='address_group_value', + address_group="address_group_value", ) + @pytest.mark.asyncio async def test_list_address_group_references_flattened_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -3872,16 +4597,18 @@ async def test_list_address_group_references_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcn_address_group.ListAddressGroupReferencesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_address_group_references( - address_group='address_group_value', + address_group="address_group_value", ) # Establish that the underlying call was made with the expected @@ -3889,9 +4616,10 @@ async def test_list_address_group_references_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].address_group - mock_val = 'address_group_value' + mock_val = "address_group_value" assert arg == mock_val + @pytest.mark.asyncio async def test_list_address_group_references_flattened_error_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -3903,7 +4631,7 @@ async def test_list_address_group_references_flattened_error_async(): with pytest.raises(ValueError): await client.list_address_group_references( gcn_address_group.ListAddressGroupReferencesRequest(), - address_group='address_group_value', + address_group="address_group_value", ) @@ -3915,8 +4643,8 @@ def test_list_address_group_references_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( gcn_address_group.ListAddressGroupReferencesResponse( @@ -3925,17 +4653,17 @@ def test_list_address_group_references_pager(transport_name: str = "grpc"): gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='abc', + next_page_token="abc", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[], - next_page_token='def', + next_page_token="def", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='ghi', + next_page_token="ghi", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ @@ -3950,11 +4678,11 @@ def test_list_address_group_references_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('address_group', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("address_group", ""),)), + ) + pager = client.list_address_group_references( + request={}, retry=retry, timeout=timeout ) - pager = client.list_address_group_references(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -3962,8 +4690,15 @@ def test_list_address_group_references_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) - for i in results) + assert all( + isinstance( + i, + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference, + ) + for i in results + ) + + def test_list_address_group_references_pages(transport_name: str = "grpc"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3972,8 +4707,8 @@ def test_list_address_group_references_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( gcn_address_group.ListAddressGroupReferencesResponse( @@ -3982,17 +4717,17 @@ def test_list_address_group_references_pages(transport_name: str = "grpc"): gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='abc', + next_page_token="abc", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[], - next_page_token='def', + next_page_token="def", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='ghi', + next_page_token="ghi", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ @@ -4003,9 +4738,10 @@ def test_list_address_group_references_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_address_group_references(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token + @pytest.mark.asyncio async def test_list_address_group_references_async_pager(): client = OrganizationAddressGroupServiceAsyncClient( @@ -4014,8 +4750,10 @@ async def test_list_address_group_references_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_address_group_references), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( gcn_address_group.ListAddressGroupReferencesResponse( @@ -4024,17 +4762,17 @@ async def test_list_address_group_references_async_pager(): gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='abc', + next_page_token="abc", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[], - next_page_token='def', + next_page_token="def", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='ghi', + next_page_token="ghi", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ @@ -4044,15 +4782,22 @@ async def test_list_address_group_references_async_pager(): ), RuntimeError, ) - async_pager = await client.list_address_group_references(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_address_group_references( + request={}, + ) + assert async_pager.next_page_token == "abc" responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) - for i in responses) + assert all( + isinstance( + i, + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference, + ) + for i in responses + ) @pytest.mark.asyncio @@ -4063,8 +4808,10 @@ async def test_list_address_group_references_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_address_group_references), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( gcn_address_group.ListAddressGroupReferencesResponse( @@ -4073,17 +4820,17 @@ async def test_list_address_group_references_async_pages(): gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='abc', + next_page_token="abc", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[], - next_page_token='def', + next_page_token="def", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='ghi', + next_page_token="ghi", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ @@ -4096,11 +4843,11 @@ async def test_list_address_group_references_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_address_group_references(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -4118,12 +4865,18 @@ def test_list_address_groups_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_address_groups in client._transport._wrapped_methods + assert ( + client._transport.list_address_groups in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_address_groups] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_address_groups + ] = mock_rpc request = {} client.list_address_groups(request) @@ -4138,57 +4891,68 @@ def test_list_address_groups_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_address_groups_rest_required_fields(request_type=address_group.ListAddressGroupsRequest): +def test_list_address_groups_rest_required_fields( + request_type=address_group.ListAddressGroupsRequest, +): transport_class = transports.OrganizationAddressGroupServiceRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_groups._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_address_groups._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = 'parent_value' + jsonified_request["parent"] = "parent_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_groups._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_address_groups._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", "return_partial_success", )) + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + "return_partial_success", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' + assert jsonified_request["parent"] == "parent_value" client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = address_group.ListAddressGroupsResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -4199,24 +4963,33 @@ def test_list_address_groups_rest_required_fields(request_type=address_group.Lis return_value = address_group.ListAddressGroupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_address_groups(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_address_groups_rest_unset_required_fields(): - transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_address_groups._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "returnPartialSuccess", )) & set(("parent", ))) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("parent",)) + ) def test_list_address_groups_rest_flattened(): @@ -4226,16 +4999,16 @@ def test_list_address_groups_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = address_group.ListAddressGroupsResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/locations/sample2'} + sample_request = {"parent": "organizations/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -4245,7 +5018,7 @@ def test_list_address_groups_rest_flattened(): # Convert return value to protobuf type return_value = address_group.ListAddressGroupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4255,10 +5028,14 @@ def test_list_address_groups_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=organizations/*/locations/*}/addressGroups" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{parent=organizations/*/locations/*}/addressGroups" + % client.transport._host, + args[1], + ) -def test_list_address_groups_rest_flattened_error(transport: str = 'rest'): +def test_list_address_groups_rest_flattened_error(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4269,20 +5046,20 @@ def test_list_address_groups_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_address_groups( address_group.ListAddressGroupsRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_address_groups_rest_pager(transport: str = 'rest'): +def test_list_address_groups_rest_pager(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: + # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( address_group.ListAddressGroupsResponse( @@ -4291,17 +5068,17 @@ def test_list_address_groups_rest_pager(transport: str = 'rest'): address_group.AddressGroup(), address_group.AddressGroup(), ], - next_page_token='abc', + next_page_token="abc", ), address_group.ListAddressGroupsResponse( address_groups=[], - next_page_token='def', + next_page_token="def", ), address_group.ListAddressGroupsResponse( address_groups=[ address_group.AddressGroup(), ], - next_page_token='ghi', + next_page_token="ghi", ), address_group.ListAddressGroupsResponse( address_groups=[ @@ -4314,24 +5091,25 @@ def test_list_address_groups_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(address_group.ListAddressGroupsResponse.to_json(x) for x in response) + response = tuple( + address_group.ListAddressGroupsResponse.to_json(x) for x in response + ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') + return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {'parent': 'organizations/sample1/locations/sample2'} + sample_request = {"parent": "organizations/sample1/locations/sample2"} pager = client.list_address_groups(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, address_group.AddressGroup) - for i in results) + assert all(isinstance(i, address_group.AddressGroup) for i in results) pages = list(client.list_address_groups(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -4353,8 +5131,12 @@ def test_get_address_group_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_address_group + ] = mock_rpc request = {} client.get_address_group(request) @@ -4369,55 +5151,60 @@ def test_get_address_group_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_address_group_rest_required_fields(request_type=address_group.GetAddressGroupRequest): +def test_get_address_group_rest_required_fields( + request_type=address_group.GetAddressGroupRequest, +): transport_class = transports.OrganizationAddressGroupServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_address_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_address_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = address_group.AddressGroup() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -4428,24 +5215,24 @@ def test_get_address_group_rest_required_fields(request_type=address_group.GetAd return_value = address_group.AddressGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_address_group(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_address_group_rest_unset_required_fields(): - transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_address_group._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_address_group_rest_flattened(): @@ -4455,16 +5242,18 @@ def test_get_address_group_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = address_group.AddressGroup() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "name": "organizations/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -4474,7 +5263,7 @@ def test_get_address_group_rest_flattened(): # Convert return value to protobuf type return_value = address_group.AddressGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4484,10 +5273,14 @@ def test_get_address_group_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=organizations/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{name=organizations/*/locations/*/addressGroups/*}" + % client.transport._host, + args[1], + ) -def test_get_address_group_rest_flattened_error(transport: str = 'rest'): +def test_get_address_group_rest_flattened_error(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4498,7 +5291,7 @@ def test_get_address_group_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_address_group( address_group.GetAddressGroupRequest(), - name='name_value', + name="name_value", ) @@ -4516,12 +5309,18 @@ def test_create_address_group_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_address_group in client._transport._wrapped_methods + assert ( + client._transport.create_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_address_group + ] = mock_rpc request = {} client.create_address_group(request) @@ -4540,7 +5339,9 @@ def test_create_address_group_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_address_group_rest_required_fields(request_type=gcn_address_group.CreateAddressGroupRequest): +def test_create_address_group_rest_required_fields( + request_type=gcn_address_group.CreateAddressGroupRequest, +): transport_class = transports.OrganizationAddressGroupServiceRestTransport request_init = {} @@ -4548,65 +5349,73 @@ def test_create_address_group_rest_required_fields(request_type=gcn_address_grou request_init["address_group_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped assert "addressGroupId" not in jsonified_request - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_address_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present assert "addressGroupId" in jsonified_request assert jsonified_request["addressGroupId"] == request_init["address_group_id"] - jsonified_request["parent"] = 'parent_value' - jsonified_request["addressGroupId"] = 'address_group_id_value' + jsonified_request["parent"] = "parent_value" + jsonified_request["addressGroupId"] = "address_group_id_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_address_group._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("address_group_id", "request_id", )) + assert not set(unset_fields) - set( + ( + "address_group_id", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' + assert jsonified_request["parent"] == "parent_value" assert "addressGroupId" in jsonified_request - assert jsonified_request["addressGroupId"] == 'address_group_id_value' + assert jsonified_request["addressGroupId"] == "address_group_id_value" client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4617,17 +5426,33 @@ def test_create_address_group_rest_required_fields(request_type=gcn_address_grou "addressGroupId", "", ), - ('$alt', 'json;enum-encoding=int') + ("$alt", "json;enum-encoding=int"), ] - actual_params = req.call_args.kwargs['params'] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_create_address_group_rest_unset_required_fields(): - transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.create_address_group._get_unset_required_fields({}) - assert set(unset_fields) == (set(("addressGroupId", "requestId", )) & set(("parent", "addressGroupId", "addressGroup", ))) + assert set(unset_fields) == ( + set( + ( + "addressGroupId", + "requestId", + ) + ) + & set( + ( + "parent", + "addressGroupId", + "addressGroup", + ) + ) + ) def test_create_address_group_rest_flattened(): @@ -4637,18 +5462,18 @@ def test_create_address_group_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'organizations/sample1/locations/sample2'} + sample_request = {"parent": "organizations/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) mock_args.update(sample_request) @@ -4656,7 +5481,7 @@ def test_create_address_group_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4666,10 +5491,14 @@ def test_create_address_group_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=organizations/*/locations/*}/addressGroups" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{parent=organizations/*/locations/*}/addressGroups" + % client.transport._host, + args[1], + ) -def test_create_address_group_rest_flattened_error(transport: str = 'rest'): +def test_create_address_group_rest_flattened_error(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4680,9 +5509,9 @@ def test_create_address_group_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.create_address_group( gcn_address_group.CreateAddressGroupRequest(), - parent='parent_value', - address_group=gcn_address_group.AddressGroup(name='name_value'), - address_group_id='address_group_id_value', + parent="parent_value", + address_group=gcn_address_group.AddressGroup(name="name_value"), + address_group_id="address_group_id_value", ) @@ -4700,12 +5529,18 @@ def test_update_address_group_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_address_group in client._transport._wrapped_methods + assert ( + client._transport.update_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_address_group + ] = mock_rpc request = {} client.update_address_group(request) @@ -4724,78 +5559,96 @@ def test_update_address_group_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_address_group_rest_required_fields(request_type=gcn_address_group.UpdateAddressGroupRequest): +def test_update_address_group_rest_required_fields( + request_type=gcn_address_group.UpdateAddressGroupRequest, +): transport_class = transports.OrganizationAddressGroupServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_address_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_address_group._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", "update_mask", )) + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_address_group(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_address_group_rest_unset_required_fields(): - transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_address_group._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("addressGroup", ))) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set(("addressGroup",)) + ) def test_update_address_group_rest_flattened(): @@ -4805,17 +5658,21 @@ def test_update_address_group_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'address_group': {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'}} + sample_request = { + "address_group": { + "name": "organizations/sample1/locations/sample2/addressGroups/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -4823,7 +5680,7 @@ def test_update_address_group_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -4833,10 +5690,14 @@ def test_update_address_group_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{address_group.name=organizations/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{address_group.name=organizations/*/locations/*/addressGroups/*}" + % client.transport._host, + args[1], + ) -def test_update_address_group_rest_flattened_error(transport: str = 'rest'): +def test_update_address_group_rest_flattened_error(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4847,8 +5708,8 @@ def test_update_address_group_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_address_group( gcn_address_group.UpdateAddressGroupRequest(), - address_group=gcn_address_group.AddressGroup(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + address_group=gcn_address_group.AddressGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -4866,12 +5727,19 @@ def test_add_address_group_items_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.add_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.add_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.add_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.add_address_group_items + ] = mock_rpc request = {} client.add_address_group_items(request) @@ -4890,7 +5758,9 @@ def test_add_address_group_items_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_add_address_group_items_rest_required_fields(request_type=gcn_address_group.AddAddressGroupItemsRequest): +def test_add_address_group_items_rest_required_fields( + request_type=gcn_address_group.AddAddressGroupItemsRequest, +): transport_class = transports.OrganizationAddressGroupServiceRestTransport request_init = {} @@ -4898,77 +5768,88 @@ def test_add_address_group_items_rest_required_fields(request_type=gcn_address_g request_init["items"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["addressGroup"] = 'address_group_value' - jsonified_request["items"] = 'items_value' + jsonified_request["addressGroup"] = "address_group_value" + jsonified_request["items"] = "items_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).add_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "addressGroup" in jsonified_request - assert jsonified_request["addressGroup"] == 'address_group_value' + assert jsonified_request["addressGroup"] == "address_group_value" assert "items" in jsonified_request - assert jsonified_request["items"] == 'items_value' + assert jsonified_request["items"] == "items_value" client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.add_address_group_items(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_add_address_group_items_rest_unset_required_fields(): - transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.add_address_group_items._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("addressGroup", "items", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "addressGroup", + "items", + ) + ) + ) def test_add_address_group_items_rest_flattened(): @@ -4978,17 +5859,19 @@ def test_add_address_group_items_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) mock_args.update(sample_request) @@ -4996,7 +5879,7 @@ def test_add_address_group_items_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -5006,10 +5889,14 @@ def test_add_address_group_items_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:addItems" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:addItems" + % client.transport._host, + args[1], + ) -def test_add_address_group_items_rest_flattened_error(transport: str = 'rest'): +def test_add_address_group_items_rest_flattened_error(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5020,8 +5907,8 @@ def test_add_address_group_items_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.add_address_group_items( gcn_address_group.AddAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) @@ -5039,12 +5926,19 @@ def test_remove_address_group_items_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.remove_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.remove_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.remove_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.remove_address_group_items + ] = mock_rpc request = {} client.remove_address_group_items(request) @@ -5063,7 +5957,9 @@ def test_remove_address_group_items_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_remove_address_group_items_rest_required_fields(request_type=gcn_address_group.RemoveAddressGroupItemsRequest): +def test_remove_address_group_items_rest_required_fields( + request_type=gcn_address_group.RemoveAddressGroupItemsRequest, +): transport_class = transports.OrganizationAddressGroupServiceRestTransport request_init = {} @@ -5071,77 +5967,88 @@ def test_remove_address_group_items_rest_required_fields(request_type=gcn_addres request_init["items"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["addressGroup"] = 'address_group_value' - jsonified_request["items"] = 'items_value' + jsonified_request["addressGroup"] = "address_group_value" + jsonified_request["items"] = "items_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).remove_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).remove_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "addressGroup" in jsonified_request - assert jsonified_request["addressGroup"] == 'address_group_value' + assert jsonified_request["addressGroup"] == "address_group_value" assert "items" in jsonified_request - assert jsonified_request["items"] == 'items_value' + assert jsonified_request["items"] == "items_value" client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.remove_address_group_items(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_remove_address_group_items_rest_unset_required_fields(): - transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.remove_address_group_items._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("addressGroup", "items", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "addressGroup", + "items", + ) + ) + ) def test_remove_address_group_items_rest_flattened(): @@ -5151,17 +6058,19 @@ def test_remove_address_group_items_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) mock_args.update(sample_request) @@ -5169,7 +6078,7 @@ def test_remove_address_group_items_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -5179,10 +6088,14 @@ def test_remove_address_group_items_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:removeItems" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:removeItems" + % client.transport._host, + args[1], + ) -def test_remove_address_group_items_rest_flattened_error(transport: str = 'rest'): +def test_remove_address_group_items_rest_flattened_error(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5193,8 +6106,8 @@ def test_remove_address_group_items_rest_flattened_error(transport: str = 'rest' with pytest.raises(ValueError): client.remove_address_group_items( gcn_address_group.RemoveAddressGroupItemsRequest(), - address_group='address_group_value', - items=['items_value'], + address_group="address_group_value", + items=["items_value"], ) @@ -5212,12 +6125,19 @@ def test_clone_address_group_items_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.clone_address_group_items in client._transport._wrapped_methods + assert ( + client._transport.clone_address_group_items + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.clone_address_group_items] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.clone_address_group_items + ] = mock_rpc request = {} client.clone_address_group_items(request) @@ -5236,7 +6156,9 @@ def test_clone_address_group_items_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_clone_address_group_items_rest_required_fields(request_type=gcn_address_group.CloneAddressGroupItemsRequest): +def test_clone_address_group_items_rest_required_fields( + request_type=gcn_address_group.CloneAddressGroupItemsRequest, +): transport_class = transports.OrganizationAddressGroupServiceRestTransport request_init = {} @@ -5244,77 +6166,88 @@ def test_clone_address_group_items_rest_required_fields(request_type=gcn_address request_init["source_address_group"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clone_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).clone_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["addressGroup"] = 'address_group_value' - jsonified_request["sourceAddressGroup"] = 'source_address_group_value' + jsonified_request["addressGroup"] = "address_group_value" + jsonified_request["sourceAddressGroup"] = "source_address_group_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).clone_address_group_items._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).clone_address_group_items._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "addressGroup" in jsonified_request - assert jsonified_request["addressGroup"] == 'address_group_value' + assert jsonified_request["addressGroup"] == "address_group_value" assert "sourceAddressGroup" in jsonified_request - assert jsonified_request["sourceAddressGroup"] == 'source_address_group_value' + assert jsonified_request["sourceAddressGroup"] == "source_address_group_value" client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.clone_address_group_items(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_clone_address_group_items_rest_unset_required_fields(): - transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.clone_address_group_items._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("addressGroup", "sourceAddressGroup", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "addressGroup", + "sourceAddressGroup", + ) + ) + ) def test_clone_address_group_items_rest_flattened(): @@ -5324,17 +6257,19 @@ def test_clone_address_group_items_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) mock_args.update(sample_request) @@ -5342,7 +6277,7 @@ def test_clone_address_group_items_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -5352,10 +6287,14 @@ def test_clone_address_group_items_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:cloneItems" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:cloneItems" + % client.transport._host, + args[1], + ) -def test_clone_address_group_items_rest_flattened_error(transport: str = 'rest'): +def test_clone_address_group_items_rest_flattened_error(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5366,8 +6305,8 @@ def test_clone_address_group_items_rest_flattened_error(transport: str = 'rest') with pytest.raises(ValueError): client.clone_address_group_items( gcn_address_group.CloneAddressGroupItemsRequest(), - address_group='address_group_value', - source_address_group='source_address_group_value', + address_group="address_group_value", + source_address_group="source_address_group_value", ) @@ -5385,12 +6324,18 @@ def test_delete_address_group_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_address_group in client._transport._wrapped_methods + assert ( + client._transport.delete_address_group in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_address_group] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_address_group + ] = mock_rpc request = {} client.delete_address_group(request) @@ -5409,57 +6354,62 @@ def test_delete_address_group_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_address_group_rest_required_fields(request_type=address_group.DeleteAddressGroupRequest): +def test_delete_address_group_rest_required_fields( + request_type=address_group.DeleteAddressGroupRequest, +): transport_class = transports.OrganizationAddressGroupServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_address_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_address_group._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_address_group._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", )) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -5467,24 +6417,24 @@ def test_delete_address_group_rest_required_fields(request_type=address_group.De response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_address_group(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_delete_address_group_rest_unset_required_fields(): - transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_address_group._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) def test_delete_address_group_rest_flattened(): @@ -5494,16 +6444,18 @@ def test_delete_address_group_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "name": "organizations/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -5511,7 +6463,7 @@ def test_delete_address_group_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -5521,10 +6473,14 @@ def test_delete_address_group_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=organizations/*/locations/*/addressGroups/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{name=organizations/*/locations/*/addressGroups/*}" + % client.transport._host, + args[1], + ) -def test_delete_address_group_rest_flattened_error(transport: str = 'rest'): +def test_delete_address_group_rest_flattened_error(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5535,7 +6491,7 @@ def test_delete_address_group_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.delete_address_group( address_group.DeleteAddressGroupRequest(), - name='name_value', + name="name_value", ) @@ -5553,12 +6509,19 @@ def test_list_address_group_references_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_address_group_references in client._transport._wrapped_methods + assert ( + client._transport.list_address_group_references + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_address_group_references] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_address_group_references + ] = mock_rpc request = {} client.list_address_group_references(request) @@ -5573,57 +6536,67 @@ def test_list_address_group_references_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_address_group_references_rest_required_fields(request_type=gcn_address_group.ListAddressGroupReferencesRequest): +def test_list_address_group_references_rest_required_fields( + request_type=gcn_address_group.ListAddressGroupReferencesRequest, +): transport_class = transports.OrganizationAddressGroupServiceRestTransport request_init = {} request_init["address_group"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_group_references._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_address_group_references._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["addressGroup"] = 'address_group_value' + jsonified_request["addressGroup"] = "address_group_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_address_group_references._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_address_group_references._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "addressGroup" in jsonified_request - assert jsonified_request["addressGroup"] == 'address_group_value' + assert jsonified_request["addressGroup"] == "address_group_value" client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = gcn_address_group.ListAddressGroupReferencesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -5631,27 +6604,39 @@ def test_list_address_group_references_rest_required_fields(request_type=gcn_add response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_address_group_references(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_address_group_references_rest_unset_required_fields(): - transport = transports.OrganizationAddressGroupServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OrganizationAddressGroupServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - unset_fields = transport.list_address_group_references._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("addressGroup", ))) + unset_fields = transport.list_address_group_references._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("addressGroup",)) + ) def test_list_address_group_references_rest_flattened(): @@ -5661,16 +6646,18 @@ def test_list_address_group_references_rest_flattened(): ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = gcn_address_group.ListAddressGroupReferencesResponse() # get arguments that satisfy an http rule for this method - sample_request = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } # get truthy value for each flattened field mock_args = dict( - address_group='address_group_value', + address_group="address_group_value", ) mock_args.update(sample_request) @@ -5678,9 +6665,11 @@ def test_list_address_group_references_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -5690,10 +6679,14 @@ def test_list_address_group_references_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:listReferences" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1/{address_group=organizations/*/locations/*/addressGroups/*}:listReferences" + % client.transport._host, + args[1], + ) -def test_list_address_group_references_rest_flattened_error(transport: str = 'rest'): +def test_list_address_group_references_rest_flattened_error(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5704,20 +6697,20 @@ def test_list_address_group_references_rest_flattened_error(transport: str = 're with pytest.raises(ValueError): client.list_address_group_references( gcn_address_group.ListAddressGroupReferencesRequest(), - address_group='address_group_value', + address_group="address_group_value", ) -def test_list_address_group_references_rest_pager(transport: str = 'rest'): +def test_list_address_group_references_rest_pager(transport: str = "rest"): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: + # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( gcn_address_group.ListAddressGroupReferencesResponse( @@ -5726,17 +6719,17 @@ def test_list_address_group_references_rest_pager(transport: str = 'rest'): gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='abc', + next_page_token="abc", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[], - next_page_token='def', + next_page_token="def", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference(), ], - next_page_token='ghi', + next_page_token="ghi", ), gcn_address_group.ListAddressGroupReferencesResponse( address_group_references=[ @@ -5749,24 +6742,34 @@ def test_list_address_group_references_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(gcn_address_group.ListAddressGroupReferencesResponse.to_json(x) for x in response) + response = tuple( + gcn_address_group.ListAddressGroupReferencesResponse.to_json(x) + for x in response + ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') + return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + sample_request = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } pager = client.list_address_group_references(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference) - for i in results) + assert all( + isinstance( + i, + gcn_address_group.ListAddressGroupReferencesResponse.AddressGroupReference, + ) + for i in results + ) pages = list(client.list_address_group_references(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -5808,8 +6811,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = OrganizationAddressGroupServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() + client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -5831,6 +6833,7 @@ def test_transport_instance(): client = OrganizationAddressGroupServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.OrganizationAddressGroupServiceGrpcTransport( @@ -5845,18 +6848,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.OrganizationAddressGroupServiceGrpcTransport, - transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, - transports.OrganizationAddressGroupServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationAddressGroupServiceGrpcTransport, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + transports.OrganizationAddressGroupServiceRestTransport, + ], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + 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_kind_grpc(): transport = OrganizationAddressGroupServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -5866,8 +6874,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -5882,8 +6889,8 @@ def test_list_address_groups_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: call.return_value = address_group.ListAddressGroupsResponse() client.list_address_groups(request=None) @@ -5905,8 +6912,8 @@ def test_get_address_group_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: call.return_value = address_group.AddressGroup() client.get_address_group(request=None) @@ -5928,9 +6935,9 @@ def test_create_address_group_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.create_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.create_address_group(request=None) # Establish that the underlying stub method was called. @@ -5951,9 +6958,9 @@ def test_update_address_group_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.update_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.update_address_group(request=None) # Establish that the underlying stub method was called. @@ -5974,9 +6981,9 @@ def test_add_address_group_items_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.add_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.add_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -5997,9 +7004,9 @@ def test_remove_address_group_items_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.remove_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.remove_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -6020,9 +7027,9 @@ def test_clone_address_group_items_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.clone_address_group_items), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.clone_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -6043,9 +7050,9 @@ def test_delete_address_group_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.delete_address_group), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.delete_address_group(request=None) # Establish that the underlying stub method was called. @@ -6066,8 +7073,8 @@ def test_list_address_group_references_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: call.return_value = gcn_address_group.ListAddressGroupReferencesResponse() client.list_address_group_references(request=None) @@ -6080,16 +7087,15 @@ def test_list_address_group_references_empty_call_grpc(): def test_transport_kind_grpc_asyncio(): - transport = OrganizationAddressGroupServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) + transport = OrganizationAddressGroupServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) assert transport.kind == "grpc_asyncio" def test_initialize_client_w_grpc_asyncio(): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -6105,13 +7111,15 @@ async def test_list_address_groups_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.ListAddressGroupsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.ListAddressGroupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) await client.list_address_groups(request=None) # Establish that the underlying stub method was called. @@ -6133,18 +7141,20 @@ async def test_get_address_group_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(address_group.AddressGroup( - name='name_value', - description='description_value', - type_=address_group.AddressGroup.Type.IPV4, - items=['items_value'], - capacity=846, - self_link='self_link_value', - purpose=[address_group.AddressGroup.Purpose.DEFAULT], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + address_group.AddressGroup( + name="name_value", + description="description_value", + type_=address_group.AddressGroup.Type.IPV4, + items=["items_value"], + capacity=846, + self_link="self_link_value", + purpose=[address_group.AddressGroup.Purpose.DEFAULT], + ) + ) await client.get_address_group(request=None) # Establish that the underlying stub method was called. @@ -6166,11 +7176,11 @@ async def test_create_address_group_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.create_address_group(request=None) @@ -6193,11 +7203,11 @@ async def test_update_address_group_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.update_address_group(request=None) @@ -6220,11 +7230,11 @@ async def test_add_address_group_items_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.add_address_group_items(request=None) @@ -6247,11 +7257,11 @@ async def test_remove_address_group_items_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.remove_address_group_items(request=None) @@ -6274,11 +7284,11 @@ async def test_clone_address_group_items_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.clone_address_group_items(request=None) @@ -6301,11 +7311,11 @@ async def test_delete_address_group_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) await client.delete_address_group(request=None) @@ -6328,12 +7338,14 @@ async def test_list_address_group_references_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcn_address_group.ListAddressGroupReferencesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcn_address_group.ListAddressGroupReferencesResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_address_group_references(request=None) # Establish that the underlying stub method was called. @@ -6351,20 +7363,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_list_address_groups_rest_bad_request(request_type=address_group.ListAddressGroupsRequest): +def test_list_address_groups_rest_bad_request( + request_type=address_group.ListAddressGroupsRequest, +): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/locations/sample2'} + request_init = {"parent": "organizations/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -6373,26 +7388,28 @@ def test_list_address_groups_rest_bad_request(request_type=address_group.ListAdd client.list_address_groups(request) -@pytest.mark.parametrize("request_type", [ - address_group.ListAddressGroupsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + address_group.ListAddressGroupsRequest, + dict, + ], +) def test_list_address_groups_rest_call_success(request_type): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/locations/sample2'} + request_init = {"parent": "organizations/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = address_group.ListAddressGroupsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) # Wrap the value into a proper Response obj @@ -6402,34 +7419,47 @@ def test_list_address_groups_rest_call_success(request_type): # Convert return value to protobuf type return_value = address_group.ListAddressGroupsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_address_groups(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_address_groups_rest_interceptors(null_interceptor): transport = transports.OrganizationAddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) client = OrganizationAddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_list_address_groups") as post, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_list_address_groups_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_list_address_groups") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_list_address_groups", + ) as post, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_list_address_groups_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "pre_list_address_groups", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = address_group.ListAddressGroupsRequest.pb(address_group.ListAddressGroupsRequest()) + pb_message = address_group.ListAddressGroupsRequest.pb( + address_group.ListAddressGroupsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6440,39 +7470,55 @@ def test_list_address_groups_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = address_group.ListAddressGroupsResponse.to_json(address_group.ListAddressGroupsResponse()) + return_value = address_group.ListAddressGroupsResponse.to_json( + address_group.ListAddressGroupsResponse() + ) req.return_value.content = return_value request = address_group.ListAddressGroupsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = address_group.ListAddressGroupsResponse() - post_with_metadata.return_value = address_group.ListAddressGroupsResponse(), metadata + post_with_metadata.return_value = ( + address_group.ListAddressGroupsResponse(), + metadata, + ) - client.list_address_groups(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_address_groups( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_address_group_rest_bad_request(request_type=address_group.GetAddressGroupRequest): +def test_get_address_group_rest_bad_request( + request_type=address_group.GetAddressGroupRequest, +): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "name": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -6481,31 +7527,35 @@ def test_get_address_group_rest_bad_request(request_type=address_group.GetAddres client.get_address_group(request) -@pytest.mark.parametrize("request_type", [ - address_group.GetAddressGroupRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + address_group.GetAddressGroupRequest, + dict, + ], +) def test_get_address_group_rest_call_success(request_type): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "name": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = address_group.AddressGroup( - name='name_value', - description='description_value', - type_=address_group.AddressGroup.Type.IPV4, - items=['items_value'], - capacity=846, - self_link='self_link_value', - purpose=[address_group.AddressGroup.Purpose.DEFAULT], + name="name_value", + description="description_value", + type_=address_group.AddressGroup.Type.IPV4, + items=["items_value"], + capacity=846, + self_link="self_link_value", + purpose=[address_group.AddressGroup.Purpose.DEFAULT], ) # Wrap the value into a proper Response obj @@ -6515,19 +7565,19 @@ def test_get_address_group_rest_call_success(request_type): # Convert return value to protobuf type return_value = address_group.AddressGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_address_group(request) # Establish that the response is the type that we expect. assert isinstance(response, address_group.AddressGroup) - assert response.name == 'name_value' - assert response.description == 'description_value' + assert response.name == "name_value" + assert response.description == "description_value" assert response.type_ == address_group.AddressGroup.Type.IPV4 - assert response.items == ['items_value'] + assert response.items == ["items_value"] assert response.capacity == 846 - assert response.self_link == 'self_link_value' + assert response.self_link == "self_link_value" assert response.purpose == [address_group.AddressGroup.Purpose.DEFAULT] @@ -6535,19 +7585,32 @@ def test_get_address_group_rest_call_success(request_type): def test_get_address_group_rest_interceptors(null_interceptor): transport = transports.OrganizationAddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) client = OrganizationAddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_get_address_group") as post, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_get_address_group_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_get_address_group") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_get_address_group", + ) as post, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_get_address_group_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "pre_get_address_group", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = address_group.GetAddressGroupRequest.pb(address_group.GetAddressGroupRequest()) + pb_message = address_group.GetAddressGroupRequest.pb( + address_group.GetAddressGroupRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6562,7 +7625,7 @@ def test_get_address_group_rest_interceptors(null_interceptor): req.return_value.content = return_value request = address_group.GetAddressGroupRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -6570,27 +7633,36 @@ def test_get_address_group_rest_interceptors(null_interceptor): post.return_value = address_group.AddressGroup() post_with_metadata.return_value = address_group.AddressGroup(), metadata - client.get_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_address_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_create_address_group_rest_bad_request(request_type=gcn_address_group.CreateAddressGroupRequest): +def test_create_address_group_rest_bad_request( + request_type=gcn_address_group.CreateAddressGroupRequest, +): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/locations/sample2'} + request_init = {"parent": "organizations/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -6599,25 +7671,40 @@ def test_create_address_group_rest_bad_request(request_type=gcn_address_group.Cr client.create_address_group(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.CreateAddressGroupRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.CreateAddressGroupRequest, + dict, + ], +) def test_create_address_group_rest_call_success(request_type): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'organizations/sample1/locations/sample2'} - request_init["address_group"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'items': ['items_value1', 'items_value2'], 'capacity': 846, 'self_link': 'self_link_value', 'purpose': [1]} + request_init = {"parent": "organizations/sample1/locations/sample2"} + request_init["address_group"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "items": ["items_value1", "items_value2"], + "capacity": 846, + "self_link": "self_link_value", + "purpose": [1], + } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = gcn_address_group.CreateAddressGroupRequest.meta.fields["address_group"] + test_field = gcn_address_group.CreateAddressGroupRequest.meta.fields[ + "address_group" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -6631,7 +7718,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -6645,7 +7732,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["address_group"].items(): # pragma: NO COVER + for field, value in request_init["address_group"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -6660,12 +7747,16 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -6678,15 +7769,15 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_address_group(request) @@ -6699,20 +7790,34 @@ def get_message_fields(field): def test_create_address_group_rest_interceptors(null_interceptor): transport = transports.OrganizationAddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) client = OrganizationAddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_create_address_group") as post, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_create_address_group_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_create_address_group") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_create_address_group", + ) as post, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_create_address_group_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "pre_create_address_group", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.CreateAddressGroupRequest.pb(gcn_address_group.CreateAddressGroupRequest()) + pb_message = gcn_address_group.CreateAddressGroupRequest.pb( + gcn_address_group.CreateAddressGroupRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6727,7 +7832,7 @@ def test_create_address_group_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gcn_address_group.CreateAddressGroupRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -6735,27 +7840,40 @@ def test_create_address_group_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.create_address_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_address_group_rest_bad_request(request_type=gcn_address_group.UpdateAddressGroupRequest): +def test_update_address_group_rest_bad_request( + request_type=gcn_address_group.UpdateAddressGroupRequest, +): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'}} + request_init = { + "address_group": { + "name": "organizations/sample1/locations/sample2/addressGroups/sample3" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -6764,25 +7882,44 @@ def test_update_address_group_rest_bad_request(request_type=gcn_address_group.Up client.update_address_group(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.UpdateAddressGroupRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.UpdateAddressGroupRequest, + dict, + ], +) def test_update_address_group_rest_call_success(request_type): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'}} - request_init["address_group"] = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'type_': 1, 'items': ['items_value1', 'items_value2'], 'capacity': 846, 'self_link': 'self_link_value', 'purpose': [1]} + request_init = { + "address_group": { + "name": "organizations/sample1/locations/sample2/addressGroups/sample3" + } + } + request_init["address_group"] = { + "name": "organizations/sample1/locations/sample2/addressGroups/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "type_": 1, + "items": ["items_value1", "items_value2"], + "capacity": 846, + "self_link": "self_link_value", + "purpose": [1], + } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = gcn_address_group.UpdateAddressGroupRequest.meta.fields["address_group"] + test_field = gcn_address_group.UpdateAddressGroupRequest.meta.fields[ + "address_group" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -6796,7 +7933,7 @@ def get_message_fields(field): if is_field_type_proto_plus_type: message_fields = field.message.meta.fields.values() # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -6810,7 +7947,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["address_group"].items(): # pragma: NO COVER + for field, value in request_init["address_group"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -6825,12 +7962,16 @@ def get_message_fields(field): for subfield in result.keys(): if (field, subfield) not in runtime_nested_fields: subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } ) # Remove fields from the sample request which are not present in the runtime version of the dependency # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER field = subfield_to_delete.get("field") field_repeated = subfield_to_delete.get("is_repeated") subfield = subfield_to_delete.get("subfield") @@ -6843,15 +7984,15 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_address_group(request) @@ -6864,20 +8005,34 @@ def get_message_fields(field): def test_update_address_group_rest_interceptors(null_interceptor): transport = transports.OrganizationAddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) client = OrganizationAddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_update_address_group") as post, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_update_address_group_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_update_address_group") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_update_address_group", + ) as post, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_update_address_group_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "pre_update_address_group", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.UpdateAddressGroupRequest.pb(gcn_address_group.UpdateAddressGroupRequest()) + pb_message = gcn_address_group.UpdateAddressGroupRequest.pb( + gcn_address_group.UpdateAddressGroupRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6892,7 +8047,7 @@ def test_update_address_group_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gcn_address_group.UpdateAddressGroupRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -6900,27 +8055,38 @@ def test_update_address_group_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_address_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_add_address_group_items_rest_bad_request(request_type=gcn_address_group.AddAddressGroupItemsRequest): +def test_add_address_group_items_rest_bad_request( + request_type=gcn_address_group.AddAddressGroupItemsRequest, +): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -6929,30 +8095,34 @@ def test_add_address_group_items_rest_bad_request(request_type=gcn_address_group client.add_address_group_items(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.AddAddressGroupItemsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.AddAddressGroupItemsRequest, + dict, + ], +) def test_add_address_group_items_rest_call_success(request_type): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.add_address_group_items(request) @@ -6965,20 +8135,34 @@ def test_add_address_group_items_rest_call_success(request_type): def test_add_address_group_items_rest_interceptors(null_interceptor): transport = transports.OrganizationAddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) client = OrganizationAddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_add_address_group_items") as post, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_add_address_group_items_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_add_address_group_items") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_add_address_group_items", + ) as post, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_add_address_group_items_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "pre_add_address_group_items", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.AddAddressGroupItemsRequest.pb(gcn_address_group.AddAddressGroupItemsRequest()) + pb_message = gcn_address_group.AddAddressGroupItemsRequest.pb( + gcn_address_group.AddAddressGroupItemsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6993,7 +8177,7 @@ def test_add_address_group_items_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gcn_address_group.AddAddressGroupItemsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -7001,27 +8185,38 @@ def test_add_address_group_items_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.add_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.add_address_group_items( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_remove_address_group_items_rest_bad_request(request_type=gcn_address_group.RemoveAddressGroupItemsRequest): +def test_remove_address_group_items_rest_bad_request( + request_type=gcn_address_group.RemoveAddressGroupItemsRequest, +): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -7030,30 +8225,34 @@ def test_remove_address_group_items_rest_bad_request(request_type=gcn_address_gr client.remove_address_group_items(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.RemoveAddressGroupItemsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.RemoveAddressGroupItemsRequest, + dict, + ], +) def test_remove_address_group_items_rest_call_success(request_type): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.remove_address_group_items(request) @@ -7066,20 +8265,34 @@ def test_remove_address_group_items_rest_call_success(request_type): def test_remove_address_group_items_rest_interceptors(null_interceptor): transport = transports.OrganizationAddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) client = OrganizationAddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_remove_address_group_items") as post, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_remove_address_group_items_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_remove_address_group_items") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_remove_address_group_items", + ) as post, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_remove_address_group_items_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "pre_remove_address_group_items", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.RemoveAddressGroupItemsRequest.pb(gcn_address_group.RemoveAddressGroupItemsRequest()) + pb_message = gcn_address_group.RemoveAddressGroupItemsRequest.pb( + gcn_address_group.RemoveAddressGroupItemsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7094,7 +8307,7 @@ def test_remove_address_group_items_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gcn_address_group.RemoveAddressGroupItemsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -7102,27 +8315,38 @@ def test_remove_address_group_items_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.remove_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.remove_address_group_items( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_clone_address_group_items_rest_bad_request(request_type=gcn_address_group.CloneAddressGroupItemsRequest): +def test_clone_address_group_items_rest_bad_request( + request_type=gcn_address_group.CloneAddressGroupItemsRequest, +): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -7131,30 +8355,34 @@ def test_clone_address_group_items_rest_bad_request(request_type=gcn_address_gro client.clone_address_group_items(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.CloneAddressGroupItemsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.CloneAddressGroupItemsRequest, + dict, + ], +) def test_clone_address_group_items_rest_call_success(request_type): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.clone_address_group_items(request) @@ -7167,20 +8395,34 @@ def test_clone_address_group_items_rest_call_success(request_type): def test_clone_address_group_items_rest_interceptors(null_interceptor): transport = transports.OrganizationAddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) client = OrganizationAddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_clone_address_group_items") as post, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_clone_address_group_items_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_clone_address_group_items") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_clone_address_group_items", + ) as post, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_clone_address_group_items_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "pre_clone_address_group_items", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.CloneAddressGroupItemsRequest.pb(gcn_address_group.CloneAddressGroupItemsRequest()) + pb_message = gcn_address_group.CloneAddressGroupItemsRequest.pb( + gcn_address_group.CloneAddressGroupItemsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7195,7 +8437,7 @@ def test_clone_address_group_items_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gcn_address_group.CloneAddressGroupItemsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -7203,27 +8445,38 @@ def test_clone_address_group_items_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.clone_address_group_items(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.clone_address_group_items( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_address_group_rest_bad_request(request_type=address_group.DeleteAddressGroupRequest): +def test_delete_address_group_rest_bad_request( + request_type=address_group.DeleteAddressGroupRequest, +): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "name": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -7232,30 +8485,34 @@ def test_delete_address_group_rest_bad_request(request_type=address_group.Delete client.delete_address_group(request) -@pytest.mark.parametrize("request_type", [ - address_group.DeleteAddressGroupRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + address_group.DeleteAddressGroupRequest, + dict, + ], +) def test_delete_address_group_rest_call_success(request_type): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "name": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_address_group(request) @@ -7268,20 +8525,34 @@ def test_delete_address_group_rest_call_success(request_type): def test_delete_address_group_rest_interceptors(null_interceptor): transport = transports.OrganizationAddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) client = OrganizationAddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_delete_address_group") as post, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_delete_address_group_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_delete_address_group") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_delete_address_group", + ) as post, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_delete_address_group_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "pre_delete_address_group", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = address_group.DeleteAddressGroupRequest.pb(address_group.DeleteAddressGroupRequest()) + pb_message = address_group.DeleteAddressGroupRequest.pb( + address_group.DeleteAddressGroupRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7296,7 +8567,7 @@ def test_delete_address_group_rest_interceptors(null_interceptor): req.return_value.content = return_value request = address_group.DeleteAddressGroupRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -7304,27 +8575,38 @@ def test_delete_address_group_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_address_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_address_group( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_address_group_references_rest_bad_request(request_type=gcn_address_group.ListAddressGroupReferencesRequest): +def test_list_address_group_references_rest_bad_request( + request_type=gcn_address_group.ListAddressGroupReferencesRequest, +): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -7333,25 +8615,29 @@ def test_list_address_group_references_rest_bad_request(request_type=gcn_address client.list_address_group_references(request) -@pytest.mark.parametrize("request_type", [ - gcn_address_group.ListAddressGroupReferencesRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gcn_address_group.ListAddressGroupReferencesRequest, + dict, + ], +) def test_list_address_group_references_rest_call_success(request_type): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'address_group': 'organizations/sample1/locations/sample2/addressGroups/sample3'} + request_init = { + "address_group": "organizations/sample1/locations/sample2/addressGroups/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = gcn_address_group.ListAddressGroupReferencesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -7359,35 +8645,50 @@ def test_list_address_group_references_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb(return_value) + return_value = gcn_address_group.ListAddressGroupReferencesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_address_group_references(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAddressGroupReferencesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_address_group_references_rest_interceptors(null_interceptor): transport = transports.OrganizationAddressGroupServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OrganizationAddressGroupServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OrganizationAddressGroupServiceRestInterceptor(), + ) client = OrganizationAddressGroupServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_list_address_group_references") as post, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "post_list_address_group_references_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OrganizationAddressGroupServiceRestInterceptor, "pre_list_address_group_references") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_list_address_group_references", + ) as post, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "post_list_address_group_references_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OrganizationAddressGroupServiceRestInterceptor, + "pre_list_address_group_references", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gcn_address_group.ListAddressGroupReferencesRequest.pb(gcn_address_group.ListAddressGroupReferencesRequest()) + pb_message = gcn_address_group.ListAddressGroupReferencesRequest.pb( + gcn_address_group.ListAddressGroupReferencesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7398,19 +8699,30 @@ def test_list_address_group_references_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = gcn_address_group.ListAddressGroupReferencesResponse.to_json(gcn_address_group.ListAddressGroupReferencesResponse()) + return_value = gcn_address_group.ListAddressGroupReferencesResponse.to_json( + gcn_address_group.ListAddressGroupReferencesResponse() + ) req.return_value.content = return_value request = gcn_address_group.ListAddressGroupReferencesRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = gcn_address_group.ListAddressGroupReferencesResponse() - post_with_metadata.return_value = gcn_address_group.ListAddressGroupReferencesResponse(), metadata + post_with_metadata.return_value = ( + gcn_address_group.ListAddressGroupReferencesResponse(), + metadata, + ) - client.list_address_group_references(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_address_group_references( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -7423,13 +8735,17 @@ def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationReq transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7438,20 +8754,23 @@ def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationReq client.get_location(request) -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) def test_get_location_rest(request_type): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2'} + request_init = {"name": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = locations_pb2.Location() @@ -7459,7 +8778,7 @@ def test_get_location_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7470,19 +8789,23 @@ def test_get_location_rest(request_type): assert isinstance(response, locations_pb2.Location) -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) + request = json_format.ParseDict({"name": "projects/sample1"}, request) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7491,20 +8814,23 @@ def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocation client.list_locations(request) -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) def test_list_locations_rest(request_type): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1'} + request_init = {"name": "projects/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = locations_pb2.ListLocationsResponse() @@ -7512,7 +8838,7 @@ def test_list_locations_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7523,19 +8849,28 @@ def test_list_locations_rest(request_type): assert isinstance(response, locations_pb2.ListLocationsResponse) -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + request = json_format.ParseDict( + { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + }, + request, + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7544,20 +8879,25 @@ def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolic client.get_iam_policy(request) -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) def test_get_iam_policy_rest(request_type): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request_init = { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = policy_pb2.Policy() @@ -7565,7 +8905,7 @@ def test_get_iam_policy_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7576,19 +8916,28 @@ def test_get_iam_policy_rest(request_type): assert isinstance(response, policy_pb2.Policy) -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + request = json_format.ParseDict( + { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + }, + request, + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7597,20 +8946,25 @@ def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolic client.set_iam_policy(request) -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) def test_set_iam_policy_rest(request_type): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request_init = { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = policy_pb2.Policy() @@ -7618,7 +8972,7 @@ def test_set_iam_policy_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7629,19 +8983,28 @@ def test_set_iam_policy_rest(request_type): assert isinstance(response, policy_pb2.Policy) -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'}, request) + request = json_format.ParseDict( + { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + }, + request, + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7650,20 +9013,25 @@ def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestI client.test_iam_permissions(request) -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) def test_test_iam_permissions_rest(request_type): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'resource': 'projects/sample1/locations/sample2/authorizationPolicies/sample3'} + request_init = { + "resource": "projects/sample1/locations/sample2/authorizationPolicies/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = iam_policy_pb2.TestIamPermissionsResponse() @@ -7671,7 +9039,7 @@ def test_test_iam_permissions_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7682,19 +9050,25 @@ def test_test_iam_permissions_rest(request_type): assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7703,28 +9077,31 @@ def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOpe client.cancel_operation(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) def test_cancel_operation_rest(request_type): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7735,19 +9112,25 @@ def test_cancel_operation_rest(request_type): assert response is None -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7756,28 +9139,31 @@ def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOpe client.delete_operation(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) def test_delete_operation_rest(request_type): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = None # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7788,19 +9174,25 @@ def test_delete_operation_rest(request_type): assert response is None -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7809,20 +9201,23 @@ def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperation client.get_operation(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) def test_get_operation_rest(request_type): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = operations_pb2.Operation() @@ -7830,7 +9225,7 @@ def test_get_operation_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7841,19 +9236,25 @@ def test_get_operation_rest(request_type): assert isinstance(response, operations_pb2.Operation) -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = Request() @@ -7862,20 +9263,23 @@ def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperat client.list_operations(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) def test_list_operations_rest(request_type): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2'} + request_init = {"name": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. return_value = operations_pb2.ListOperationsResponse() @@ -7883,7 +9287,7 @@ def test_list_operations_rest(request_type): response_value = mock.Mock() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -7893,10 +9297,10 @@ def test_list_operations_rest(request_type): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + def test_initialize_client_w_rest(): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -7911,8 +9315,8 @@ def test_list_address_groups_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_groups), - '__call__') as call: + type(client.transport.list_address_groups), "__call__" + ) as call: client.list_address_groups(request=None) # Establish that the underlying stub method was called. @@ -7933,8 +9337,8 @@ def test_get_address_group_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_address_group), - '__call__') as call: + type(client.transport.get_address_group), "__call__" + ) as call: client.get_address_group(request=None) # Establish that the underlying stub method was called. @@ -7955,8 +9359,8 @@ def test_create_address_group_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_address_group), - '__call__') as call: + type(client.transport.create_address_group), "__call__" + ) as call: client.create_address_group(request=None) # Establish that the underlying stub method was called. @@ -7977,8 +9381,8 @@ def test_update_address_group_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_address_group), - '__call__') as call: + type(client.transport.update_address_group), "__call__" + ) as call: client.update_address_group(request=None) # Establish that the underlying stub method was called. @@ -7999,8 +9403,8 @@ def test_add_address_group_items_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.add_address_group_items), - '__call__') as call: + type(client.transport.add_address_group_items), "__call__" + ) as call: client.add_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -8021,8 +9425,8 @@ def test_remove_address_group_items_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.remove_address_group_items), - '__call__') as call: + type(client.transport.remove_address_group_items), "__call__" + ) as call: client.remove_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -8043,8 +9447,8 @@ def test_clone_address_group_items_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.clone_address_group_items), - '__call__') as call: + type(client.transport.clone_address_group_items), "__call__" + ) as call: client.clone_address_group_items(request=None) # Establish that the underlying stub method was called. @@ -8065,8 +9469,8 @@ def test_delete_address_group_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_address_group), - '__call__') as call: + type(client.transport.delete_address_group), "__call__" + ) as call: client.delete_address_group(request=None) # Establish that the underlying stub method was called. @@ -8087,8 +9491,8 @@ def test_list_address_group_references_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_address_group_references), - '__call__') as call: + type(client.transport.list_address_group_references), "__call__" + ) as call: client.list_address_group_references(request=None) # Establish that the underlying stub method was called. @@ -8109,12 +9513,13 @@ def test_organization_address_group_service_rest_lro_client(): # Ensure that we have an api-core operations client. assert isinstance( transport.operations_client, -operations_v1.AbstractOperationsClient, + operations_v1.AbstractOperationsClient, ) # Ensure that subsequent calls to the property send the exact same object. assert transport.operations_client is transport.operations_client + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = OrganizationAddressGroupServiceClient( @@ -8125,18 +9530,21 @@ def test_transport_grpc_default(): transports.OrganizationAddressGroupServiceGrpcTransport, ) + def test_organization_address_group_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.OrganizationAddressGroupServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_organization_address_group_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.cloud.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceTransport.__init__') as Transport: + with mock.patch( + "google.cloud.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.OrganizationAddressGroupServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -8145,24 +9553,24 @@ def test_organization_address_group_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'list_address_groups', - 'get_address_group', - 'create_address_group', - 'update_address_group', - 'add_address_group_items', - 'remove_address_group_items', - 'clone_address_group_items', - 'delete_address_group', - 'list_address_group_references', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', + "list_address_groups", + "get_address_group", + "create_address_group", + "update_address_group", + "add_address_group_items", + "remove_address_group_items", + "clone_address_group_items", + "delete_address_group", + "list_address_group_references", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", ) for method in methods: with pytest.raises(NotImplementedError): @@ -8178,7 +9586,7 @@ def test_organization_address_group_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -8187,25 +9595,30 @@ def test_organization_address_group_service_base_transport(): def test_organization_address_group_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.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.OrganizationAddressGroupServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + load_creds.assert_called_once_with( + "credentials.json", scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) def test_organization_address_group_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.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.network_security_v1.services.organization_address_group_service.transports.OrganizationAddressGroupServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.OrganizationAddressGroupServiceTransport() @@ -8214,14 +9627,12 @@ def test_organization_address_group_service_base_transport_with_adc(): def test_organization_address_group_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) OrganizationAddressGroupServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id=None, ) @@ -8236,12 +9647,12 @@ def test_organization_address_group_service_auth_adc(): def test_organization_address_group_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: + 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',), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) @@ -8254,49 +9665,53 @@ def test_organization_address_group_service_transport_auth_adc(transport_class): transports.OrganizationAddressGroupServiceRestTransport, ], ) -def test_organization_address_group_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] +def test_organization_address_group_service_transport_auth_gdch_credentials( + transport_class, +): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) adc.return_value = (gdch_mock, None) transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) + gdch_mock.with_gdch_audience.assert_called_once_with(e) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.OrganizationAddressGroupServiceGrpcTransport, grpc_helpers), - (transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, grpc_helpers_async) + ( + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + grpc_helpers_async, + ), ], ) -def test_organization_address_group_service_transport_create_channel(transport_class, grpc_helpers): +def test_organization_address_group_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( + 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"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "networksecurity.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=["1", "2"], default_host="networksecurity.googleapis.com", ssl_credentials=None, @@ -8307,9 +9722,15 @@ def test_organization_address_group_service_transport_create_channel(transport_c ) -@pytest.mark.parametrize("transport_class", [transports.OrganizationAddressGroupServiceGrpcTransport, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationAddressGroupServiceGrpcTransport, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + ], +) def test_organization_address_group_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -8319,7 +9740,7 @@ def test_organization_address_group_service_grpc_transport_client_cert_source_fo transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -8340,62 +9761,80 @@ def test_organization_address_group_service_grpc_transport_client_cert_source_fo with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + 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 + certificate_chain=expected_cert, private_key=expected_key ) + def test_organization_address_group_service_http_transport_client_cert_source_for_mtls(): cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.OrganizationAddressGroupServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.OrganizationAddressGroupServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_organization_address_group_service_host_no_port(transport_name): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com'), - transport=transport_name, + client_options=client_options.ClientOptions( + api_endpoint="networksecurity.googleapis.com" + ), + transport=transport_name, ) assert client.transport._host == ( - 'networksecurity.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networksecurity.googleapis.com' + "networksecurity.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com" ) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_organization_address_group_service_host_with_port(transport_name): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='networksecurity.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="networksecurity.googleapis.com:8000" + ), transport=transport_name, ) assert client.transport._host == ( - 'networksecurity.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://networksecurity.googleapis.com:8000' + "networksecurity.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://networksecurity.googleapis.com:8000" ) -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_organization_address_group_service_client_transport_session_collision(transport_name): + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_organization_address_group_service_client_transport_session_collision( + transport_name, +): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() client1 = OrganizationAddressGroupServiceClient( @@ -8433,8 +9872,10 @@ def test_organization_address_group_service_client_transport_session_collision(t session1 = client1.transport.list_address_group_references._session session2 = client2.transport.list_address_group_references._session assert session1 != session2 + + def test_organization_address_group_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.OrganizationAddressGroupServiceGrpcTransport( @@ -8447,7 +9888,7 @@ def test_organization_address_group_service_grpc_transport_channel(): def test_organization_address_group_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport( @@ -8461,12 +9902,22 @@ def test_organization_address_group_service_grpc_asyncio_transport_channel(): # 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.OrganizationAddressGroupServiceGrpcTransport, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationAddressGroupServiceGrpcTransport, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + ], +) def test_organization_address_group_service_transport_channel_mtls_with_client_cert_source( - transport_class + 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: + 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 @@ -8475,7 +9926,7 @@ def test_organization_address_group_service_transport_channel_mtls_with_client_c cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -8505,9 +9956,15 @@ def test_organization_address_group_service_transport_channel_mtls_with_client_c # 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.OrganizationAddressGroupServiceGrpcTransport, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationAddressGroupServiceGrpcTransport, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + ], +) def test_organization_address_group_service_transport_channel_mtls_with_adc( - transport_class + transport_class, ): mock_ssl_cred = mock.Mock() with mock.patch.multiple( @@ -8515,7 +9972,9 @@ def test_organization_address_group_service_transport_channel_mtls_with_adc( __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: + 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() @@ -8546,7 +10005,7 @@ def test_organization_address_group_service_transport_channel_mtls_with_adc( def test_organization_address_group_service_grpc_lro_client(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -8563,7 +10022,7 @@ def test_organization_address_group_service_grpc_lro_client(): def test_organization_address_group_service_grpc_lro_async_client(): client = OrganizationAddressGroupServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', + transport="grpc_asyncio", ) transport = client.transport @@ -8581,8 +10040,16 @@ def test_address_group_path(): project = "squid" location = "clam" address_group = "whelk" - expected = "projects/{project}/locations/{location}/addressGroups/{address_group}".format(project=project, location=location, address_group=address_group, ) - actual = OrganizationAddressGroupServiceClient.address_group_path(project, location, address_group) + expected = ( + "projects/{project}/locations/{location}/addressGroups/{address_group}".format( + project=project, + location=location, + address_group=address_group, + ) + ) + actual = OrganizationAddressGroupServiceClient.address_group_path( + project, location, address_group + ) assert expected == actual @@ -8598,10 +10065,15 @@ def test_parse_address_group_path(): actual = OrganizationAddressGroupServiceClient.parse_address_group_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = OrganizationAddressGroupServiceClient.common_billing_account_path(billing_account) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = OrganizationAddressGroupServiceClient.common_billing_account_path( + billing_account + ) assert expected == actual @@ -8612,12 +10084,17 @@ def test_parse_common_billing_account_path(): path = OrganizationAddressGroupServiceClient.common_billing_account_path(**expected) # Check that the path construction is reversible. - actual = OrganizationAddressGroupServiceClient.parse_common_billing_account_path(path) + actual = OrganizationAddressGroupServiceClient.parse_common_billing_account_path( + path + ) assert expected == actual + def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = OrganizationAddressGroupServiceClient.common_folder_path(folder) assert expected == actual @@ -8632,10 +10109,15 @@ def test_parse_common_folder_path(): actual = OrganizationAddressGroupServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = OrganizationAddressGroupServiceClient.common_organization_path(organization) + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = OrganizationAddressGroupServiceClient.common_organization_path( + organization + ) assert expected == actual @@ -8649,9 +10131,12 @@ def test_parse_common_organization_path(): actual = OrganizationAddressGroupServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = OrganizationAddressGroupServiceClient.common_project_path(project) assert expected == actual @@ -8666,11 +10151,17 @@ def test_parse_common_project_path(): actual = OrganizationAddressGroupServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = OrganizationAddressGroupServiceClient.common_location_path(project, location) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = OrganizationAddressGroupServiceClient.common_location_path( + project, location + ) assert expected == actual @@ -8689,14 +10180,18 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.OrganizationAddressGroupServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.OrganizationAddressGroupServiceTransport, "_prep_wrapped_messages" + ) as prep: client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.OrganizationAddressGroupServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.OrganizationAddressGroupServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = OrganizationAddressGroupServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -8707,7 +10202,8 @@ def test_client_with_default_client_info(): def test_delete_operation(transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -8726,10 +10222,13 @@ def test_delete_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert response is None + + @pytest.mark.asyncio async def test_delete_operation_async(transport: str = "grpc_asyncio"): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -8739,9 +10238,7 @@ async def test_delete_operation_async(transport: str = "grpc_asyncio"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_operation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8751,6 +10248,7 @@ async def test_delete_operation_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert response is None + def test_delete_operation_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8763,7 +10261,7 @@ def test_delete_operation_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None + call.return_value = None client.delete_operation(request) # Establish that the underlying gRPC stub method was called. @@ -8773,7 +10271,12 @@ def test_delete_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_delete_operation_field_headers_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -8787,9 +10290,7 @@ async def test_delete_operation_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_operation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8798,7 +10299,11 @@ async def test_delete_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_delete_operation_from_dict(): client = OrganizationAddressGroupServiceClient( @@ -8815,6 +10320,8 @@ def test_delete_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_delete_operation_from_dict_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -8823,9 +10330,7 @@ async def test_delete_operation_from_dict_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_operation( request={ "name": "locations", @@ -8836,7 +10341,8 @@ async def test_delete_operation_from_dict_async(): def test_cancel_operation(transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -8855,10 +10361,13 @@ def test_cancel_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert response is None + + @pytest.mark.asyncio async def test_cancel_operation_async(transport: str = "grpc_asyncio"): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -8868,9 +10377,7 @@ async def test_cancel_operation_async(transport: str = "grpc_asyncio"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.cancel_operation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8880,6 +10387,7 @@ async def test_cancel_operation_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert response is None + def test_cancel_operation_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8892,7 +10400,7 @@ def test_cancel_operation_field_headers(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None + call.return_value = None client.cancel_operation(request) # Establish that the underlying gRPC stub method was called. @@ -8902,7 +10410,12 @@ def test_cancel_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_cancel_operation_field_headers_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -8916,9 +10429,7 @@ async def test_cancel_operation_field_headers_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.cancel_operation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8927,7 +10438,11 @@ async def test_cancel_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_cancel_operation_from_dict(): client = OrganizationAddressGroupServiceClient( @@ -8944,6 +10459,8 @@ def test_cancel_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_cancel_operation_from_dict_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -8952,9 +10469,7 @@ async def test_cancel_operation_from_dict_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.cancel_operation( request={ "name": "locations", @@ -8965,7 +10480,8 @@ async def test_cancel_operation_from_dict_async(): def test_get_operation(transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -8984,10 +10500,13 @@ def test_get_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) + + @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc_asyncio"): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9009,6 +10528,7 @@ async def test_get_operation_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) + def test_get_operation_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9031,7 +10551,12 @@ def test_get_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9056,7 +10581,11 @@ async def test_get_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_get_operation_from_dict(): client = OrganizationAddressGroupServiceClient( @@ -9073,6 +10602,8 @@ def test_get_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9094,7 +10625,8 @@ async def test_get_operation_from_dict_async(): def test_list_operations(transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9113,10 +10645,13 @@ def test_list_operations(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + + @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc_asyncio"): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9138,6 +10673,7 @@ async def test_list_operations_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + def test_list_operations_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9160,7 +10696,12 @@ def test_list_operations_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9185,7 +10726,11 @@ async def test_list_operations_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_list_operations_from_dict(): client = OrganizationAddressGroupServiceClient( @@ -9202,6 +10747,8 @@ def test_list_operations_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9223,7 +10770,8 @@ async def test_list_operations_from_dict_async(): def test_list_locations(transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9242,10 +10790,13 @@ def test_list_locations(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.ListLocationsResponse) + + @pytest.mark.asyncio async def test_list_locations_async(transport: str = "grpc_asyncio"): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9267,6 +10818,7 @@ async def test_list_locations_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.ListLocationsResponse) + def test_list_locations_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9289,7 +10841,12 @@ def test_list_locations_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_list_locations_field_headers_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9314,7 +10871,11 @@ async def test_list_locations_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_list_locations_from_dict(): client = OrganizationAddressGroupServiceClient( @@ -9331,6 +10892,8 @@ def test_list_locations_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_list_locations_from_dict_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9352,7 +10915,8 @@ async def test_list_locations_from_dict_async(): def test_get_location(transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9371,10 +10935,13 @@ def test_get_location(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.Location) + + @pytest.mark.asyncio async def test_get_location_async(transport: str = "grpc_asyncio"): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9396,9 +10963,11 @@ async def test_get_location_async(transport: str = "grpc_asyncio"): # Establish that the response is the type that we expect. assert isinstance(response, locations_pb2.Location) + def test_get_location_field_headers(): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials()) + credentials=ga_credentials.AnonymousCredentials() + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -9417,7 +10986,12 @@ def test_get_location_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_get_location_field_headers_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9442,7 +11016,11 @@ async def test_get_location_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + def test_get_location_from_dict(): client = OrganizationAddressGroupServiceClient( @@ -9459,6 +11037,8 @@ def test_get_location_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_get_location_from_dict_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9480,7 +11060,8 @@ async def test_get_location_from_dict_async(): def test_set_iam_policy(transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9490,7 +11071,10 @@ def test_set_iam_policy(transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) response = client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9504,10 +11088,13 @@ def test_set_iam_policy(transport: str = "grpc"): assert response.version == 774 assert response.etag == b"etag_blob" + + @pytest.mark.asyncio async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9519,7 +11106,10 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): # Designate an appropriate return value for the call. # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) ) response = await client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -9535,6 +11125,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): assert response.etag == b"etag_blob" + def test_set_iam_policy_field_headers(): client = OrganizationAddressGroupServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9558,7 +11149,12 @@ def test_set_iam_policy_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9583,7 +11179,11 @@ async def test_set_iam_policy_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + def test_set_iam_policy_from_dict(): client = OrganizationAddressGroupServiceClient( @@ -9611,9 +11211,7 @@ async def test_set_iam_policy_from_dict_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.set_iam_policy( request={ @@ -9623,9 +11221,11 @@ async def test_set_iam_policy_from_dict_async(): ) call.assert_called() + def test_get_iam_policy(transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9635,7 +11235,10 @@ def test_get_iam_policy(transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) response = client.get_iam_policy(request) @@ -9656,7 +11259,8 @@ def test_get_iam_policy(transport: str = "grpc"): @pytest.mark.asyncio async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9664,12 +11268,13 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): request = iam_policy_pb2.GetIamPolicyRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) ) response = await client.get_iam_policy(request) @@ -9711,7 +11316,10 @@ def test_get_iam_policy_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -9726,9 +11334,7 @@ async def test_get_iam_policy_field_headers_async(): request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.get_iam_policy(request) @@ -9740,7 +11346,10 @@ async def test_get_iam_policy_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] def test_get_iam_policy_from_dict(): @@ -9760,6 +11369,7 @@ def test_get_iam_policy_from_dict(): ) call.assert_called() + @pytest.mark.asyncio async def test_get_iam_policy_from_dict_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9768,9 +11378,7 @@ async def test_get_iam_policy_from_dict_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.get_iam_policy( request={ @@ -9780,9 +11388,11 @@ async def test_get_iam_policy_from_dict_async(): ) call.assert_called() + def test_test_iam_permissions(transport: str = "grpc"): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9815,7 +11425,8 @@ def test_test_iam_permissions(transport: str = "grpc"): @pytest.mark.asyncio async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, + credentials=async_anonymous_credentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -9828,7 +11439,9 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) response = await client.test_iam_permissions(request) @@ -9870,7 +11483,10 @@ def test_test_iam_permissions_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -9901,7 +11517,10 @@ async def test_test_iam_permissions_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] def test_test_iam_permissions_from_dict(): @@ -9923,6 +11542,7 @@ def test_test_iam_permissions_from_dict(): ) call.assert_called() + @pytest.mark.asyncio async def test_test_iam_permissions_from_dict_async(): client = OrganizationAddressGroupServiceAsyncClient( @@ -9948,10 +11568,11 @@ async def test_test_iam_permissions_from_dict_async(): def test_transport_close_grpc(): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() @@ -9960,10 +11581,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = OrganizationAddressGroupServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: async with client: close.assert_not_called() close.assert_called_once() @@ -9971,10 +11593,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() @@ -9982,13 +11605,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = OrganizationAddressGroupServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -9997,10 +11619,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (OrganizationAddressGroupServiceClient, transports.OrganizationAddressGroupServiceGrpcTransport), - (OrganizationAddressGroupServiceAsyncClient, transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + OrganizationAddressGroupServiceClient, + transports.OrganizationAddressGroupServiceGrpcTransport, + ), + ( + OrganizationAddressGroupServiceAsyncClient, + transports.OrganizationAddressGroupServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -10015,7 +11647,9 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None,